dqn_statebuilder.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. from typing import Dict
  2. from dataclasses import replace
  3. import numpy as np
  4. import pandas as pd
  5. from sklearn.metrics import r2_score
  6. from env.env_params import UFState
  7. from uf_data_process.load import UFConfigLoader
  8. from uf_data_process.label import UFEventClassifier, PostBackwashInletMarker
  9. from uf_data_process.filter import ConstantFlowFilter,EventQualityFilter, InletSegmentFilter,FlowOutlierFilter
  10. from uf_data_process.calculate import UFResistanceCalculator, UFResistanceAnalyzer
  11. from uf_data_process.fit import ShortTermCycleFoulingFitter, LongTermFoulingFitter
  12. class DQNStateBuilder:
  13. """
  14. 在 DQN 决策前构建状态的工具类
  15. 相关数据:
  16. * CSV1 = 上一完整化学周期
  17. * CSV2 = 新周期初始进水段
  18. * CSV3 = 新周期预测进水段
  19. """
  20. def __init__(self, config_path: str):
  21. """
  22. Parameters
  23. ----------
  24. config_path : str
  25. uf_analyze_config.yaml 路径
  26. """
  27. self.cfg = UFConfigLoader(config_path)
  28. uf_cfg = self.cfg.uf
  29. params = self.cfg.params
  30. self.units = uf_cfg.get("units", ["UF1", "UF2", "UF3", "UF4"])
  31. self.stable_inlet_code = uf_cfg.get("stable_inlet_code", [24.0, 26.0])
  32. column_formats = uf_cfg.get("column_formats", {})
  33. self.ctrl_format = column_formats.get("ctrl_col", "C.M.{unit}_DB@word_control")
  34. self.flow_format = column_formats.get("flow_col", "C.M.{unit}_FT_JS@out")
  35. self.tmp_format = column_formats.get("tmp_col", "C.M.{unit}_DB@press_PV")
  36. self.per_format = column_formats.get("per_col", "{unit}Per")
  37. self.temp_col = column_formats.get("temp_col", "C.M.RO_TT_ZJS@out")
  38. # 过滤器
  39. self.min_points = params.get("min_points", 20)
  40. self.initial_points = params.get("initial_points", 10)
  41. self.quality_filter = EventQualityFilter(min_points=self.min_points)
  42. self.flow_filter = FlowOutlierFilter(n_sigma=3)
  43. self.initial_label = PostBackwashInletMarker(n_points=self.initial_points)
  44. # 阻力计算器
  45. self.res_calc = UFResistanceCalculator(self.units, area_m2=uf_cfg["area_m2"], scale_factor=params.get("scale_factor", 1e10))
  46. self.segment_head_n = params.get("segment_head_n", 10)
  47. self.segment_tail_n = params.get("segment_tail_n", 10)
  48. # ======================================================================
  49. # 对外主接口
  50. # ======================================================================
  51. def build_from_csv_pair(
  52. self,
  53. unit_name,
  54. uf_state_default,
  55. state_bounds,
  56. prev_cycle_csv: str,
  57. init_cycle_csv: str,
  58. predict_cycle_csv: str,
  59. ) -> UFState:
  60. """
  61. 使用【上一完整化学周期 CSV】+【当前周期初始 CSV】+ 【当前周期预测 CSV】构建 UFState
  62. """
  63. df_prev = pd.read_csv(prev_cycle_csv)
  64. df_init = pd.read_csv(init_cycle_csv)
  65. df_predict = pd.read_csv(predict_cycle_csv)
  66. # 分别处理两个 CSV
  67. prev_features = self._analyze_previous_cycle_csv(df_prev, unit_name, uf_state_default, state_bounds)
  68. init_features = self._analyze_init_cycle_csv(df_init, unit_name, uf_state_default, state_bounds)
  69. # 化学清洗去除阻力(上一周期末 - 当前初始)
  70. ceb_removal = max(
  71. prev_features["R_end"] - init_features["R_start"],
  72. 0.0
  73. )
  74. # 使用df_predict修正 nuk
  75. corrected_nuk = self._correct_nuk_with_predict(
  76. df_predict=df_predict,
  77. unit_name=unit_name,
  78. R_start=init_features["R_start"],
  79. q_mean=init_features["q_mean"],
  80. temp_celsius=init_features["temp_mean"],
  81. base_nuk=prev_features["nuK"],
  82. uf_state_default=uf_state_default,
  83. )
  84. # 构建 UFState
  85. current_state = replace(
  86. uf_state_default,
  87. TMP=init_features["tmp_mean"],
  88. q_UF=init_features["q_mean"],
  89. temp=init_features["temp_mean"],
  90. R = init_features["R_start"],
  91. nuK = corrected_nuk,
  92. slope=prev_features["slope"],
  93. power=prev_features["power"],
  94. ceb_removal=ceb_removal,
  95. )
  96. return current_state
  97. # ======================================================================
  98. # 上一完整化学周期分析
  99. # ======================================================================
  100. def _analyze_previous_cycle_csv(
  101. self,
  102. df,
  103. unit_name,
  104. uf_state_default,
  105. state_bounds
  106. ) -> Dict[str, float]:
  107. """
  108. 上一完整化学周期分析逻辑
  109. 步骤:
  110. 1. 事件标注
  111. 2. 进水段过滤(质量过滤)
  112. 3. 膜阻力计算
  113. 4. 提取周期末稳定阻力
  114. 5. 拟合 nuK
  115. 6. 拟合长期不可逆污染(slope / power)
  116. """
  117. ctrl_col = self.ctrl_format.format(unit=unit_name)
  118. flow_col = self.flow_format.format(unit=unit_name)
  119. tmp_col = self.tmp_format.format(unit=unit_name)
  120. # 事件标注
  121. event_clf = UFEventClassifier(unit_name, self.cfg.uf["inlet_codes"],
  122. self.cfg.uf["physical_bw_code"], self.cfg.uf["chemical_bw_code"],
  123. ctrl_col)
  124. df_unit = event_clf.classify(df) # 产生 event_type 列
  125. df_unit_mark = self.initial_label.mark(df_unit) # 标记反冲洗事件后的前 N 个进水点
  126. seg_df = event_clf.segment(df_unit_mark) # 根据 event_type 列编号事件段落
  127. # 对 seg_df 进行按 segment 分组后逐段过滤:
  128. const_flow_filter = ConstantFlowFilter(flow_col=flow_col, repeat_len=20)
  129. segments = const_flow_filter.filter(seg_df) # 去除出现网络错误的进水段
  130. segments = self.quality_filter.filter(segments) # 去除时间过短的进水段
  131. # 提取稳定进水段
  132. stable_extractor = InletSegmentFilter(ctrl_col, stable_codes=self.stable_inlet_code, min_points=self.min_points)
  133. stable_segments = stable_extractor.extract(segments) # 提取稳定进水数据
  134. if len(stable_segments) == 0:
  135. raise ValueError("上一周期无有效稳定进水段,无法构建状态,请使用run_dqn_decide.py")
  136. # 膜阻力计算
  137. stable_segments = self.res_calc.calculate_for_segments(
  138. stable_segments,
  139. temp_col=self.temp_col,
  140. flow_col=flow_col,
  141. tmp_col=tmp_col,
  142. )
  143. # -------- 膜阻力统计 --------
  144. res_col = f"{unit_name}_R_scaled"
  145. ura = UFResistanceAnalyzer(
  146. resistance_col=res_col,
  147. head_n=self.segment_head_n,
  148. tail_n=self.segment_tail_n
  149. )
  150. stable_segments = ura.analyze_segments(stable_segments)
  151. df_all = stable_segments[-1]
  152. R_end = df_all["R_scaled_end"].iloc[0]
  153. # ===== 确保 time 为 datetime =====
  154. for i, seg in enumerate(stable_segments):
  155. if not pd.api.types.is_datetime64_any_dtype(seg["time"]):
  156. seg = seg.copy()
  157. seg["time"] = pd.to_datetime(seg["time"], errors="coerce")
  158. seg = seg.dropna(subset=["time"])
  159. stable_segments[i] = seg
  160. # -------- 5️⃣ 短期污染拟合(nuK)--------
  161. st_fitter = ShortTermCycleFoulingFitter(unit_name)
  162. nuK, st_r2 = st_fitter.fit_cycle(stable_segments)
  163. if (
  164. pd.isna(nuK)
  165. or pd.isna(st_r2)
  166. or not np.isfinite(nuK)
  167. or st_r2 < 0.4
  168. ):
  169. nuK = uf_state_default.nuK
  170. # -------- 6️⃣ 长期不可逆污染拟合 --------
  171. lt_fitter = LongTermFoulingFitter(unit_name)
  172. slope, power, lt_r2 = lt_fitter.fit_cycle(stable_segments)
  173. if (
  174. pd.isna(slope)
  175. or pd.isna(power)
  176. or pd.isna(lt_r2)
  177. or not np.isfinite(slope)
  178. or not np.isfinite(power)
  179. or lt_r2 < 0.4
  180. ):
  181. slope = uf_state_default.slope
  182. power = uf_state_default.power
  183. return {
  184. "R_end": R_end,
  185. "nuK": float(nuK),
  186. "slope": float(slope),
  187. "power": float(power),
  188. }
  189. # ======================================================================
  190. # 当前周期初始进水段分析
  191. # ======================================================================
  192. def _analyze_init_cycle_csv(
  193. self,
  194. df,
  195. unit_name,
  196. uf_state_default,
  197. state_bounds
  198. ) -> Dict[str, float]:
  199. """
  200. 当前周期初始进水段分析
  201. """
  202. flow_col = self.flow_format.format(unit=unit_name)
  203. tmp_col = self.tmp_format.format(unit=unit_name)
  204. temp_col = self.temp_col
  205. res_col = f"{unit_name}_R_scaled"
  206. segments = [df]
  207. segments = self.res_calc.calculate_for_segments(
  208. segments,
  209. temp_col=self.temp_col,
  210. flow_col=flow_col,
  211. tmp_col=tmp_col,
  212. )
  213. df = segments[-1]
  214. return {
  215. "q_mean": float(df[flow_col].mean()),
  216. "tmp_mean": float(df[tmp_col].mean()),
  217. "temp_mean": float(df[temp_col].mean()),
  218. "R_start": float(df[res_col].mean()),
  219. }
  220. def _correct_nuk_with_predict(
  221. self,
  222. df_predict,
  223. unit_name,
  224. R_start,
  225. q_mean,
  226. temp_celsius,
  227. base_nuk,
  228. uf_state_default,
  229. ):
  230. """
  231. 使用 predict_csv 中预测的渗透率,
  232. 对短期污染参数 nuK 进行在线修正。
  233. """
  234. per_col = self.per_format.format(unit=unit_name)
  235. if per_col not in df_predict.columns:
  236. return base_nuk
  237. per = pd.to_numeric(
  238. df_predict[per_col],
  239. errors="coerce"
  240. )
  241. mask = (
  242. np.isfinite(per)
  243. & (per > 0)
  244. )
  245. per = per[mask]
  246. if len(per) < 5:
  247. return base_nuk
  248. mu = self.res_calc.xishan_viscosity(temp_celsius)
  249. R = 3.6e11 / (mu * per)
  250. R_scaled = R / self.res_calc.scale_factor
  251. R_scaled = (R_scaled- R_scaled.iloc[0]+ R_start)
  252. t = np.arange(len(R_scaled)) * 60.0
  253. J_const = q_mean / self.res_calc.A / 3600.0
  254. if not np.isfinite(J_const) or J_const <= 0:
  255. return base_nuk
  256. x = J_const * t
  257. try:
  258. coef = np.polyfit(x, R_scaled, 1)
  259. predict_nuk = float(coef[0])
  260. pred = np.polyval(coef, x)
  261. r2 = r2_score(R_scaled, pred)
  262. except Exception:
  263. return base_nuk
  264. if (
  265. not np.isfinite(r2)
  266. or not np.isfinite(predict_nuk)
  267. or predict_nuk <= 0
  268. or r2 < 0.4
  269. ):
  270. return base_nuk
  271. corrected_nuk = (
  272. 0.7 * base_nuk
  273. + 0.3 * predict_nuk
  274. )
  275. if (
  276. not np.isfinite(corrected_nuk)
  277. or corrected_nuk <= 0
  278. ):
  279. return uf_state_default.nuK
  280. return float(corrected_nuk)