DQN_decide.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import numpy as np
  2. from stable_baselines3 import DQN
  3. from UF_super_RL.DQN_env import UFSuperCycleEnv
  4. from UF_super_RL.DQN_env import UFParams
  5. # 模型路径
  6. MODEL_PATH = "dqn_model.zip"
  7. # 加载模型(只加载一次,提高效率)
  8. model = DQN.load(MODEL_PATH)
  9. def run_uf_DQN_decide(uf_params, TMP0_value: float):
  10. """
  11. 单步决策函数:输入原始 TMP0,预测并执行动作
  12. 参数:
  13. TMP0_value (float): 当前 TMP0 值(单位与环境一致)
  14. 返回:
  15. dict: 包含模型选择的动作、动作参数、新状态、奖励等
  16. """
  17. # 1. 实例化环境
  18. base_params = uf_params
  19. env = UFSuperCycleEnv(base_params)
  20. # 2. 将输入的 TMP0 写入环境
  21. env.current_params.TMP0 = TMP0_value
  22. # 3. 获取归一化状态
  23. obs = env._get_obs().reshape(1, -1)
  24. # 4. 模型预测动作
  25. action, _ = model.predict(obs, deterministic=True)
  26. # 5. 解析动作对应的 L_s 和 t_bw_s
  27. L_s, t_bw_s = env._get_action_values(action[0])
  28. # 6. 在环境中执行该动作
  29. next_obs, reward, terminated, truncated, info = env.step(action[0])
  30. # 7. 整理结果
  31. result = {
  32. "action": int(action[0]),
  33. "L_s": float(L_s),
  34. "t_bw_s": float(t_bw_s),
  35. "next_obs": next_obs,
  36. "reward": reward,
  37. "terminated": terminated,
  38. "truncated": truncated,
  39. "info": info
  40. }
  41. # 8. 关闭环境
  42. env.close()
  43. return result
  44. def generate_plc_instructions(current_L_s, current_t_bw_s, model_prev_L_s, model_prev_t_bw_s, model_L_s, model_t_bw_s):
  45. """
  46. 根据工厂当前值、模型上一轮决策值和模型当前轮决策值,生成PLC指令。
  47. 新增功能:
  48. 1. 处理None值情况:如果模型上一轮值为None,则使用工厂当前值;
  49. 如果工厂当前值也为None,则返回None并提示错误。
  50. """
  51. # 参数配置保持不变
  52. params = UFParams(
  53. L_min_s=3600.0, L_max_s=6000.0, L_step_s=60.0,
  54. t_bw_min_s=40.0, t_bw_max_s=60.0, t_bw_step_s=5.0,
  55. )
  56. # 参数解包
  57. L_step_s = params.L_step_s
  58. t_bw_step_s = params.t_bw_step_s
  59. L_min_s = params.L_min_s
  60. L_max_s = params.L_max_s
  61. t_bw_min_s = params.t_bw_min_s
  62. t_bw_max_s = params.t_bw_max_s
  63. adjustment_threshold = 1.0
  64. # 处理None值情况
  65. if model_prev_L_s is None:
  66. if current_L_s is None:
  67. print("错误: 过滤时长的工厂当前值和模型上一轮值均为None")
  68. return None, None
  69. else:
  70. # 使用工厂当前值作为基准
  71. effective_current_L = current_L_s
  72. source_L = "工厂当前值(模型上一轮值为None)"
  73. else:
  74. # 模型上一轮值不为None,继续检查工厂当前值
  75. if current_L_s is None:
  76. effective_current_L = model_prev_L_s
  77. source_L = "模型上一轮值(工厂当前值为None)"
  78. else:
  79. effective_current_L = model_prev_L_s
  80. source_L = "模型上一轮值"
  81. # 对反洗时长进行同样的处理
  82. if model_prev_t_bw_s is None:
  83. if current_t_bw_s is None:
  84. print("错误: 反洗时长的工厂当前值和模型上一轮值均为None")
  85. return None, None
  86. else:
  87. effective_current_t_bw = current_t_bw_s
  88. source_t_bw = "工厂当前值(模型上一轮值为None)"
  89. else:
  90. if current_t_bw_s is None:
  91. effective_current_t_bw = model_prev_t_bw_s
  92. source_t_bw = "模型上一轮值(工厂当前值为None)"
  93. else:
  94. effective_current_t_bw = model_prev_t_bw_s
  95. source_t_bw = "模型上一轮值"
  96. # 检测所有输入值是否在规定范围内(只对非None值进行检查)
  97. # 工厂当前值检查(警告)
  98. if current_L_s is not None and not (L_min_s <= current_L_s <= L_max_s):
  99. print(f"警告: 当前过滤时长 {current_L_s} 秒不在允许范围内 [{L_min_s}, {L_max_s}]")
  100. if current_t_bw_s is not None and not (t_bw_min_s <= current_t_bw_s <= t_bw_max_s):
  101. print(f"警告: 当前反洗时长 {current_t_bw_s} 秒不在允许范围内 [{t_bw_min_s}, {t_bw_max_s}]")
  102. # 模型上一轮决策值检查(警告)
  103. if model_prev_L_s is not None and not (L_min_s <= model_prev_L_s <= L_max_s):
  104. print(f"警告: 模型上一轮过滤时长 {model_prev_L_s} 秒不在允许范围内 [{L_min_s}, {L_max_s}]")
  105. if model_prev_t_bw_s is not None and not (t_bw_min_s <= model_prev_t_bw_s <= t_bw_max_s):
  106. print(f"警告: 模型上一轮反洗时长 {model_prev_t_bw_s} 秒不在允许范围内 [{t_bw_min_s}, {t_bw_max_s}]")
  107. # 模型当前轮决策值检查(错误)
  108. if model_L_s is None:
  109. raise ValueError("错误: 决策模型建议的过滤时长不能为None")
  110. elif not (L_min_s <= model_L_s <= L_max_s):
  111. raise ValueError(f"错误: 决策模型建议的过滤时长 {model_L_s} 秒不在允许范围内 [{L_min_s}, {L_max_s}]")
  112. if model_t_bw_s is None:
  113. raise ValueError("错误: 决策模型建议的反洗时长不能为None")
  114. elif not (t_bw_min_s <= model_t_bw_s <= t_bw_max_s):
  115. raise ValueError(f"错误: 决策模型建议的反洗时长 {model_t_bw_s} 秒不在允许范围内 [{t_bw_min_s}, {t_bw_max_s}]")
  116. print(f"过滤时长基准: {source_L}, 值: {effective_current_L}")
  117. print(f"反洗时长基准: {source_t_bw}, 值: {effective_current_t_bw}")
  118. # 使用选定的基准值进行计算调整
  119. L_diff = model_L_s - effective_current_L
  120. L_adjustment = 0
  121. if abs(L_diff) >= adjustment_threshold * L_step_s:
  122. if L_diff >= 0:
  123. L_adjustment = L_step_s
  124. else:
  125. L_adjustment = -L_step_s
  126. next_L_s = effective_current_L + L_adjustment
  127. t_bw_diff = model_t_bw_s - effective_current_t_bw
  128. t_bw_adjustment = 0
  129. if abs(t_bw_diff) >= adjustment_threshold * t_bw_step_s:
  130. if t_bw_diff >= 0:
  131. t_bw_adjustment = t_bw_step_s
  132. else:
  133. t_bw_adjustment = -t_bw_step_s
  134. next_t_bw_s = effective_current_t_bw + t_bw_adjustment
  135. return next_L_s, next_t_bw_s
  136. from UF_super_RL.DQN_env import simulate_one_supercycle
  137. def calc_uf_cycle_metrics(p, TMP0, max_tmp_during_filtration, min_tmp_during_filtration, L_s: float, t_bw_s: float):
  138. """
  139. 计算 UF 超滤系统的核心性能指标
  140. 参数:
  141. p (UFParams): UF 系统参数
  142. L_s (float): 单次过滤时间(秒)
  143. t_bw_s (float): 单次反洗时间(秒)
  144. 返回:
  145. dict: {
  146. "k_bw_per_ceb": 小周期次数,
  147. "ton_water_energy_kWh_per_m3": 吨水电耗,
  148. "recovery": 回收率,
  149. "net_delivery_rate_m3ph": 净供水率 (m³/h),
  150. "daily_prod_time_h": 日均产水时间 (小时/天)
  151. "max_permeability": 全周期最高渗透率(lmh/bar)
  152. }
  153. """
  154. # 将跨膜压差写入参数
  155. p.TMP0 = TMP0
  156. # 模拟该参数下的超级周期
  157. feasible, info = simulate_one_supercycle(p, L_s, t_bw_s)
  158. # 获得模型模拟周期信息
  159. k_bw_per_ceb = info["k_bw_per_ceb"]
  160. ton_water_energy_kWh_per_m3 = info["ton_water_energy_kWh_per_m3"]
  161. recovery = info["recovery"]
  162. net_delivery_rate_m3ph = info["net_delivery_rate_m3ph"]
  163. daily_prod_time_h = info["daily_prod_time_h"]
  164. # 获得模型模拟周期内最高跨膜压差/最低跨膜压差
  165. if max_tmp_during_filtration is None:
  166. max_tmp_during_filtration = info["max_TMP_during_filtration"]
  167. if min_tmp_during_filtration is None:
  168. min_tmp_during_filtration = info["min_TMP_during_filtration"]
  169. # 计算最高渗透率
  170. max_permeability = 100 * p.q_UF / (128*40) / min_tmp_during_filtration
  171. return {
  172. "k_bw_per_ceb": k_bw_per_ceb,
  173. "ton_water_energy_kWh_per_m3": ton_water_energy_kWh_per_m3,
  174. "recovery": recovery,
  175. "net_delivery_rate_m3ph": net_delivery_rate_m3ph,
  176. "daily_prod_time_h": daily_prod_time_h,
  177. "max_permeability": max_permeability
  178. }
  179. # ==============================
  180. # 示例调用
  181. # ==============================
  182. if __name__ == "__main__":
  183. uf_params = UFParams()
  184. TMP0 = 0.03 # 原始 TMP0
  185. model_decide_result = run_uf_DQN_decide(uf_params, TMP0) # 调用模型获得动作
  186. model_L_s = model_decide_result['L_s'] # 获得模型决策产水时长
  187. model_t_bw_s = model_decide_result['t_bw_s'] # 获得模型决策反洗时长
  188. current_L_s = 3800
  189. current_t_bw_s = 40
  190. model_prev_L_s = 4040
  191. model_prev_t_bw_s = 60
  192. L_s, t_bw_s = generate_plc_instructions(current_L_s, current_t_bw_s, model_prev_L_s, model_prev_t_bw_s, model_L_s, model_t_bw_s) # 获取模型下发指令
  193. L_s = 4100
  194. t_bw_s = 96
  195. max_tmp_during_filtration = 0.050176 # 新增工厂数据接口:周期最高/最低跨膜压差,无工厂数据接入时传入None,calc_uf_cycle_metrics()自动获取模拟周期中的跨膜压差最值
  196. min_tmp_during_filtration = 0.012496
  197. execution_result = calc_uf_cycle_metrics(uf_params, TMP0, max_tmp_during_filtration, min_tmp_during_filtration, L_s, t_bw_s)
  198. print("\n===== 单步决策结果 =====")
  199. print(f"模型选择的动作: {model_decide_result['action']}")
  200. print(f"模型选择的L_s: {model_L_s} 秒, 模型选择的t_bw_s: {model_t_bw_s} 秒")
  201. print(f"指令下发的L_s: {L_s} 秒, 指令下发的t_bw_s: {t_bw_s} 秒")
  202. print(f"指令对应的反洗次数: {execution_result['k_bw_per_ceb']}")
  203. print(f"指令对应的吨水电耗: {execution_result['ton_water_energy_kWh_per_m3']}")
  204. print(f"指令对应的回收率: {execution_result['recovery']}")
  205. print(f"指令对应的日均产水时间: {execution_result['daily_prod_time_h']}")
  206. print(f"指令对应的最高渗透率: {execution_result['max_permeability']}")