【Time Shaft·时间轴 V1.2发布声明】命劫开发


Time Shaft·时间轴 version 1.2 正式发布了!

Alpha 版本功能

功能列表详情图:
模块 功能
登录 用户通过邮箱和密码登录
注册 用户通过邮箱验证码方式注册
好友/团队列表 查看好友以及团队列表,可以修改备注,查看个人信息、好友信息和团队信息
修改密码 通过邮箱验证对密码进行修改
创建团队 创建自己的团队
添加好友/团队 通过模糊搜索支持添加好友申请,加入团队申请
好友/团队邀请 接收添加好友信息和团队邀请信息
聊天列表 展示即时通讯聊天列表
即时通讯 和好友进行即时通讯,和好友愉快的聊天
好友时间轴 添加记录和好友的动态事件,展现在我们的时间轴当中
内容概要:本文介绍了一个基于MATLAB实现的无人机三维路径规划项目,采用蚁群算法(ACO)与多层感知机(MLP)相结合的混合模型(ACO-MLP)。该模型通过三维环境离散化建模,利用ACO进行全局路径搜索,并引入MLP对环境特征进行自适应学习与启发因子优化,实现路径的动态调整与多目标优化。项目解决了高维空间建模、动态障碍规避、局部最优陷阱、算法实时性及多目标权衡等关键技术难题,结合并行计算与参数自适应机制,提升了路径规划的智能性、安全性和工程适用性。文中提供了详细的模型架构、核心算法流程及MATLAB代码示例,涵盖空间建模、信息素更新、MLP训练与融合优化等关键步骤。; 适合人群:具备一定MATLAB编程基础,熟悉智能优化算法与神经网络的高校学生、科研人员及从事无人机路径规划相关工作的工程师;适合从事智能无人系统、自动驾驶、机器人导航等领域的研究人员; 使用场景及目标:①应用于复杂三维环境下的无人机路径规划,如城市物流、灾害救援、军事侦察等场景;②实现飞行安全、能耗优化、路径平滑与实时避障等多目标协同优化;③为智能无人系统的自主决策与环境适应能力提供算法支持; 阅读建议:此资源结合理论模型与MATLAB实践,建议读者在理解ACO与MLP基本原理的基础上,结合代码示例进行仿真调试,重点关注ACO-MLP融合机制、多目标优化函数设计及参数自适应策略的实现,以深入掌握混合智能算法在工程中的应用方法。
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}") 在此代码的基础上,在约束条件上加入t时刻风机i的风速真实值减去t时刻风机i的风速测量值的绝对值小于等于0.1*真实值,t时刻风机i的功率真实值减去t时刻风机i的功率测量值的绝对值小于等于0.1*真实值
07-20
你希望在当前的 **遗传算法优化模型中加入新的约束条件**,即: - 对于任意时间步 $ t $ 和风机 $ i $: - $ |v_{i,t}^{\text{measured}} - v_{i,t}^{\text{true}}| \leq 0.1 \cdot v_{i,t}^{\text{true}} $ - $ |p_{i,t}^{\text{measured}} - p_{i,t}^{\text{true}}| \leq 0.1 \cdot p_{i,t}^{\text{true}} $ 这表示**功率和风速的测量值与真实值之间的误差不超过 ±10%**。 --- ## ✅ 解决思路 ### 1. **新增数据输入:真实功率与真实风速** 你需要读取两个新数据源: - `true_power_data.xlsx`:真实功率值(用于判断误差) - `true_wind_speed_data.xlsx`:真实风速值(用于判断误差) ### 2. **在遗传算法的目标函数中添加误差约束惩罚项** 如果某个风机的测量值与真实值的误差超过 ±10%,则在目标函数中引入惩罚项,使其适应度值变差。 --- ## ✅ 修改后的完整代码(新增约束) ```python 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' # 原始功率数据文件 input_true_power_file = 'true_power_data.xlsx' # 新增:真实功率数据 input_true_wind_file = 'true_wind_speed_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 load_true_data(power_path, wind_path): true_power = pd.read_excel(power_path, header=None).values true_wind = pd.read_excel(wind_path, header=None).values num_turbines = 100 num_time_steps = 2000 true_power_list = [] true_wind_list = [] for i in range(num_turbines): start = i * num_time_steps end = start + num_time_steps true_power_list.append(true_power[start:end, 1]) true_wind_list.append(true_wind[start:end, 1]) return np.array(true_power_list), np.array(true_wind_list) # (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, true_power, true_wind): 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 # 新增:测量误差约束惩罚项 power_error = np.mean(np.abs(powers - true_power) / (np.abs(true_power) + 1e-6)) wind_error = np.mean(np.abs(powers - true_wind) / (np.abs(true_wind) + 1e-6)) # 如果误差超过10%,引入惩罚 power_penalty = 1e3 * np.sum((np.abs(powers - true_power) > 0.1 * np.abs(true_power))) wind_penalty = 1e3 * np.sum((np.abs(powers - true_wind) > 0.1 * np.abs(true_wind))) # 总目标函数 = 损伤 + 惩罚项 final_objective = total_damage + power_penalty + wind_penalty return final_objective, # ================== 功率限制函数 ================== 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, true_power, true_wind): 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, true_power=true_power, true_wind=true_wind) 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_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, true_power, true_wind)[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) # Step 2: 加载真实功率与风速数据 true_power_data, true_wind_data = load_true_data(input_true_power_file, input_true_wind_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] # 获取真实值 true_power = true_power_data[:, t] true_wind = true_wind_data[:, t] opt_powers, damage_after = optimize_ga(shaft_t, tower_f, power_initial, true_power, true_wind) 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), true_power, true_wind)[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_with_noise_constraint.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}") ``` --- ## ✅ 新增功能说明 | 模块 | 功能 | |------|------| | `load_true_data` | 读取真实功率和风速数据 | | `objective_function` | 新增误差惩罚项,确保测量值与真实值误差在 ±10% 内 | | `optimize_ga` | 传入真实功率与风速参数 | | `动画显示` | 保留实时动画展示优化过程 | --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值