run_dqn_decide.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. """
  2. run_dqn_decide.py
  3. UF 超滤 DQN 决策主入口(Inference / Online Assist)
  4. 职责:
  5. 1. 构造物理世界(physics)
  6. 2. 实例化决策器(UFDQNDecider)
  7. 3. 构造当前工厂状态(observation)
  8. 4. 调用模型给出策略建议
  9. 5. 生成 PLC 下发指令(限幅 / 限速)
  10. 6. 评估该指令在物理模型下的效果(只评估,不下发)
  11. """
  12. from pathlib import Path
  13. import numpy as np
  14. # ========== 参数 / 物理 ==========
  15. from uf_train.env.uf_resistance_models_load import load_resistance_models
  16. from uf_train.env.uf_physics import UFPhysicsModel
  17. from uf_train.env.env_params import UFState, UFPhysicsParams, UFStateBounds, UFRewardParams, UFActionSpec
  18. # ========== 决策器 ==========
  19. from uf_train.rl_model.DQN.dqn_decider import UFDQNDecider
  20. def build_physics():
  21. """
  22. 构造与训练一致的物理模型(只做一次)
  23. """
  24. phys_params = UFPhysicsParams()
  25. res_fp, res_bw = load_resistance_models(phys_params)
  26. physics = UFPhysicsModel(
  27. phys_params=phys_params,
  28. resistance_model_fp=res_fp,
  29. resistance_model_bw=res_bw,
  30. )
  31. return physics
  32. 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):
  33. """
  34. 根据工厂当前值、模型上一轮决策值和模型当前轮决策值,生成PLC指令。
  35. 新增功能:
  36. 1. 处理None值情况:如果模型上一轮值为None,则使用工厂当前值;
  37. 如果工厂当前值也为None,则返回None并提示错误。
  38. """
  39. action_spec = UFActionSpec()
  40. adjustment_threshold = 1.0
  41. # 处理None值情况
  42. if model_prev_L_s is None:
  43. if current_L_s is None:
  44. print("错误: 过滤时长的工厂当前值和模型上一轮值均为None")
  45. return None, None
  46. else:
  47. # 使用工厂当前值作为基准
  48. effective_current_L = current_L_s
  49. source_L = "工厂当前值(模型上一轮值为None)"
  50. else:
  51. # 模型上一轮值不为None,继续检查工厂当前值
  52. if current_L_s is None:
  53. effective_current_L = model_prev_L_s
  54. source_L = "模型上一轮值(工厂当前值为None)"
  55. else:
  56. effective_current_L = model_prev_L_s
  57. source_L = "模型上一轮值"
  58. # 对反洗时长进行同样的处理
  59. if model_prev_t_bw_s is None:
  60. if current_t_bw_s is None:
  61. print("错误: 反洗时长的工厂当前值和模型上一轮值均为None")
  62. return None, None
  63. else:
  64. effective_current_t_bw = current_t_bw_s
  65. source_t_bw = "工厂当前值(模型上一轮值为None)"
  66. else:
  67. if current_t_bw_s is None:
  68. effective_current_t_bw = model_prev_t_bw_s
  69. source_t_bw = "模型上一轮值(工厂当前值为None)"
  70. else:
  71. effective_current_t_bw = model_prev_t_bw_s
  72. source_t_bw = "模型上一轮值"
  73. # 检测所有输入值是否在规定范围内(只对非None值进行检查)
  74. # 工厂当前值检查(警告)
  75. if current_L_s is not None and not (action_spec.L_min_s <= current_L_s <= action_spec.L_max_s):
  76. print(f"警告: 当前过滤时长 {current_L_s} 秒不在允许范围内 [{action_spec.L_min_s}, {action_spec.L_max_s}]")
  77. if current_t_bw_s is not None and not (action_spec.t_bw_min_s <= current_t_bw_s <= action_spec.t_bw_max_s):
  78. print(f"警告: 当前反洗时长 {current_t_bw_s} 秒不在允许范围内 [{action_spec.t_bw_min_s}, {action_spec.t_bw_max_s}]")
  79. # 模型上一轮决策值检查(警告)
  80. if model_prev_L_s is not None and not (action_spec.L_min_s <= model_prev_L_s <= action_spec.L_max_s):
  81. print(f"警告: 模型上一轮过滤时长 {model_prev_L_s} 秒不在允许范围内 [{action_spec.L_min_s}, {action_spec.L_max_s}]")
  82. if model_prev_t_bw_s is not None and not (action_spec.t_bw_min_s <= model_prev_t_bw_s <= action_spec.t_bw_max_s):
  83. print(f"警告: 模型上一轮反洗时长 {model_prev_t_bw_s} 秒不在允许范围内 [{action_spec.t_bw_min_s}, {action_spec.t_bw_max_s}]")
  84. # 模型当前轮决策值检查(错误)
  85. if model_L_s is None:
  86. raise ValueError("错误: 决策模型建议的过滤时长不能为None")
  87. elif not (action_spec.L_min_s <= model_L_s <= action_spec.L_max_s):
  88. raise ValueError(f"错误: 决策模型建议的过滤时长 {model_L_s} 秒不在允许范围内 [{action_spec.L_min_s}, {action_spec.L_max_s}]")
  89. if model_t_bw_s is None:
  90. raise ValueError("错误: 决策模型建议的反洗时长不能为None")
  91. elif not (action_spec.t_bw_min_s <= model_t_bw_s <= action_spec.t_bw_max_s):
  92. raise ValueError(f"错误: 决策模型建议的反洗时长 {model_t_bw_s} 秒不在允许范围内 [{action_spec.t_bw_min_s}, {action_spec.t_bw_max_s}]")
  93. print(f"过滤时长基准: {source_L}, 值: {effective_current_L}")
  94. print(f"反洗时长基准: {source_t_bw}, 值: {effective_current_t_bw}")
  95. # 使用选定的基准值进行计算调整
  96. L_diff = model_L_s - effective_current_L
  97. L_adjustment = 0
  98. if abs(L_diff) >= adjustment_threshold * action_spec.L_step_s:
  99. if L_diff >= 0:
  100. L_adjustment = action_spec.L_step_s
  101. else:
  102. L_adjustment = -action_spec.L_step_s
  103. next_L_s = effective_current_L + L_adjustment
  104. t_bw_diff = model_t_bw_s - effective_current_t_bw
  105. t_bw_adjustment = 0
  106. if abs(t_bw_diff) >= adjustment_threshold * action_spec.t_bw_step_s:
  107. if t_bw_diff >= 0:
  108. t_bw_adjustment = action_spec.t_bw_step_s
  109. else:
  110. t_bw_adjustment = -action_spec.t_bw_step_s
  111. next_t_bw_s = effective_current_t_bw + t_bw_adjustment
  112. return next_L_s, next_t_bw_s
  113. def calc_uf_cycle_metrics(current_state, max_tmp_during_filtration, min_tmp_during_filtration, L_s: float, t_bw_s: float):
  114. """
  115. 计算 UF 超滤系统的核心性能指标
  116. 参数:
  117. L_s (float): 单次过滤时间(秒)
  118. t_bw_s (float): 单次反洗时间(秒)
  119. 返回:
  120. dict: {
  121. "k_bw_per_ceb": 小周期次数,
  122. "ton_water_energy_kWh_per_m3": 吨水电耗,
  123. "recovery": 回收率,
  124. "net_delivery_rate_m3ph": 净供水率 (m³/h),
  125. "daily_prod_time_h": 日均产水时间 (小时/天)
  126. "max_permeability": 全周期最高渗透率(lmh/bar)
  127. }
  128. """
  129. # 模拟该参数下的超级周期
  130. info, next_state = physics.simulate_one_supercycle(current_state, L_s=L_s, t_bw_s=t_bw_s)
  131. # 获得模型模拟周期信息
  132. k_bw_per_ceb = info["k_bw_per_ceb"]
  133. ton_water_energy_kWh_per_m3 = info["ton_water_energy_kWh_per_m3"]
  134. recovery = info["recovery"]
  135. daily_prod_time_h = info["daily_prod_time_h"]
  136. # 获得模型模拟周期内最高跨膜压差/最低跨膜压差
  137. if max_tmp_during_filtration is None:
  138. max_tmp_during_filtration = info["max_TMP_during_filtration"]
  139. if min_tmp_during_filtration is None:
  140. min_tmp_during_filtration = info["min_TMP_during_filtration"]
  141. # 计算最高渗透率
  142. max_permeability = 100 * current_state.q_UF / (128*40) / min_tmp_during_filtration
  143. return {
  144. "k_bw_per_ceb": k_bw_per_ceb,
  145. "ton_water_energy_kWh_per_m3": ton_water_energy_kWh_per_m3,
  146. "recovery": recovery,
  147. "daily_prod_time_h": daily_prod_time_h,
  148. "max_permeability": max_permeability
  149. }
  150. def run_dqn_decide(
  151. model_path: Path,
  152. physics,
  153. # -------- 工厂当前值 --------
  154. current_state: UFState
  155. ):
  156. """
  157. 单轮 DQN 决策流程
  158. """
  159. # 构造决策器
  160. decider = UFDQNDecider(
  161. physics=physics,
  162. model_path=model_path,
  163. seed=0,
  164. )
  165. # 模型决策(不推进真实环境)
  166. decision = decider.decide(current_state)
  167. action_id = decision["action_id"]
  168. model_L_s = decision["L_s"]
  169. model_t_bw_s = decision["t_bw_s"]
  170. return action_id, model_L_s, model_t_bw_s
  171. # ==============================
  172. # 示例调用
  173. # ==============================
  174. if __name__ == "__main__":
  175. MODEL_PATH = "model/dqn_model.zip"
  176. TMP0 = 0.019 # 原始 TMP0
  177. q_UF = 300 # 进水流量
  178. temp = 20.0 #进水温度
  179. current_state = UFState(TMP=TMP0, q_UF=q_UF, temp=temp)
  180. physics = build_physics()
  181. action_id, model_L_s, model_t_bw_s = run_dqn_decide(
  182. model_path=MODEL_PATH,
  183. physics=physics,
  184. current_state=current_state,
  185. ) # 环境实例化,模型加载等功能放在UFDQNDecider类中
  186. current_L_s = 3800
  187. current_t_bw_s = 40
  188. model_prev_L_s = 4040
  189. model_prev_t_bw_s = 60
  190. 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,
  191. model_t_bw_s) # 获取模型下发指令
  192. L_s = 4100
  193. t_bw_s = 96
  194. max_tmp_during_filtration = 0.050176 # 新增工厂数据接口:周期最高/最低跨膜压差,无工厂数据接入时传入None,calc_uf_cycle_metrics()自动获取模拟周期中的跨膜压差最值
  195. min_tmp_during_filtration = 0.012496
  196. execution_result = calc_uf_cycle_metrics(current_state, max_tmp_during_filtration, min_tmp_during_filtration, L_s, t_bw_s)
  197. print("\n===== 单步决策结果 =====")
  198. print(f"模型选择的动作: {action_id}")
  199. print(f"模型选择的L_s: {model_L_s} 秒, 模型选择的t_bw_s: {model_t_bw_s} 秒")
  200. print(f"指令下发的L_s: {L_s} 秒, 指令下发的t_bw_s: {t_bw_s} 秒")
  201. print(f"指令对应的反洗次数: {execution_result['k_bw_per_ceb']}")
  202. print(f"指令对应的吨水电耗: {execution_result['ton_water_energy_kWh_per_m3']}")
  203. print(f"指令对应的回收率: {execution_result['recovery']}")
  204. print(f"指令对应的日均产水时间: {execution_result['daily_prod_time_h']}")
  205. print(f"指令对应的最高渗透率: {execution_result['max_permeability']}")