dqn_statebuilder.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. from typing import Dict, Optional
  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: Optional[str] = None,
  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. # predict_csv 允许为空
  66. df_predict = None
  67. if predict_cycle_csv is not None:
  68. df_predict = pd.read_csv(predict_cycle_csv)
  69. # 分别处理两个 CSV
  70. prev_features = self._analyze_previous_cycle_csv(
  71. df_prev,
  72. unit_name,
  73. uf_state_default,
  74. state_bounds
  75. )
  76. init_features = self._analyze_init_cycle_csv(
  77. df_init,
  78. unit_name,
  79. uf_state_default,
  80. state_bounds
  81. )
  82. # 化学清洗去除阻力(上一周期末 - 当前初始)
  83. ceb_removal = max(
  84. prev_features["R_end"] - init_features["R_start"],
  85. 0.0
  86. )
  87. # 默认直接使用上一周期 nuK
  88. corrected_nuk = prev_features["nuK"]
  89. # 如果提供了 predict_csv,则进行在线修正
  90. if df_predict is not None:
  91. corrected_nuk = self._correct_nuk_with_predict(
  92. df_predict=df_predict,
  93. unit_name=unit_name,
  94. R_start=init_features["R_start"],
  95. q_mean=init_features["q_mean"],
  96. temp_celsius=init_features["temp_mean"],
  97. base_nuk=prev_features["nuK"],
  98. uf_state_default=uf_state_default,
  99. )
  100. # 构建 UFState
  101. current_state = replace(
  102. uf_state_default,
  103. TMP=init_features["tmp_mean"],
  104. q_UF=init_features["q_mean"],
  105. temp=init_features["temp_mean"],
  106. R=init_features["R_start"],
  107. nuK=corrected_nuk,
  108. slope=prev_features["slope"],
  109. power=prev_features["power"],
  110. ceb_removal=ceb_removal,
  111. )
  112. return current_state
  113. # ======================================================================
  114. # 上一完整化学周期分析
  115. # ======================================================================
  116. def _analyze_previous_cycle_csv(
  117. self,
  118. df,
  119. unit_name,
  120. uf_state_default,
  121. state_bounds
  122. ) -> Dict[str, float]:
  123. """
  124. 上一完整化学周期分析逻辑
  125. 步骤:
  126. 1. 事件标注
  127. 2. 进水段过滤(质量过滤)
  128. 3. 膜阻力计算
  129. 4. 提取周期末稳定阻力
  130. 5. 拟合 nuK
  131. 6. 拟合长期不可逆污染(slope / power)
  132. """
  133. ctrl_col = self.ctrl_format.format(unit=unit_name)
  134. flow_col = self.flow_format.format(unit=unit_name)
  135. tmp_col = self.tmp_format.format(unit=unit_name)
  136. # 事件标注
  137. event_clf = UFEventClassifier(unit_name, self.cfg.uf["inlet_codes"],
  138. self.cfg.uf["physical_bw_code"], self.cfg.uf["chemical_bw_code"],
  139. ctrl_col)
  140. df_unit = event_clf.classify(df) # 产生 event_type 列
  141. df_unit_mark = self.initial_label.mark(df_unit) # 标记反冲洗事件后的前 N 个进水点
  142. seg_df = event_clf.segment(df_unit_mark) # 根据 event_type 列编号事件段落
  143. # 对 seg_df 进行按 segment 分组后逐段过滤:
  144. const_flow_filter = ConstantFlowFilter(flow_col=flow_col, repeat_len=20)
  145. segments = const_flow_filter.filter(seg_df) # 去除出现网络错误的进水段
  146. segments = self.quality_filter.filter(segments) # 去除时间过短的进水段
  147. # 提取稳定进水段
  148. stable_extractor = InletSegmentFilter(ctrl_col, stable_codes=self.stable_inlet_code, min_points=self.min_points)
  149. stable_segments = stable_extractor.extract(segments) # 提取稳定进水数据
  150. if len(stable_segments) == 0:
  151. raise ValueError("上一周期无有效稳定进水段,无法构建状态,请使用run_dqn_decide.py")
  152. # 膜阻力计算
  153. stable_segments = self.res_calc.calculate_for_segments(
  154. stable_segments,
  155. temp_col=self.temp_col,
  156. flow_col=flow_col,
  157. tmp_col=tmp_col,
  158. )
  159. # -------- 膜阻力统计 --------
  160. res_col = f"{unit_name}_R_scaled"
  161. ura = UFResistanceAnalyzer(
  162. resistance_col=res_col,
  163. head_n=self.segment_head_n,
  164. tail_n=self.segment_tail_n
  165. )
  166. stable_segments = ura.analyze_segments(stable_segments)
  167. df_all = stable_segments[-1]
  168. R_end = df_all["R_scaled_end"].iloc[0]
  169. # ===== 确保 time 为 datetime =====
  170. for i, seg in enumerate(stable_segments):
  171. if not pd.api.types.is_datetime64_any_dtype(seg["time"]):
  172. seg = seg.copy()
  173. seg["time"] = pd.to_datetime(seg["time"], errors="coerce")
  174. seg = seg.dropna(subset=["time"])
  175. stable_segments[i] = seg
  176. # -------- 5️⃣ 短期污染拟合(nuK)--------
  177. st_fitter = ShortTermCycleFoulingFitter(unit_name)
  178. nuK, st_r2 = st_fitter.fit_cycle(stable_segments)
  179. if (
  180. pd.isna(nuK)
  181. or pd.isna(st_r2)
  182. or not np.isfinite(nuK)
  183. or st_r2 < 0.4
  184. ):
  185. nuK = uf_state_default.nuK
  186. nuK = float(
  187. np.clip(
  188. nuK,
  189. state_bounds.nuK_min,
  190. state_bounds.nuK_max,
  191. )
  192. )
  193. # -------- 6️⃣ 长期不可逆污染拟合 --------
  194. lt_fitter = LongTermFoulingFitter(unit_name)
  195. slope, power, lt_r2 = lt_fitter.fit_cycle(stable_segments)
  196. if (
  197. pd.isna(slope)
  198. or pd.isna(power)
  199. or pd.isna(lt_r2)
  200. or not np.isfinite(slope)
  201. or not np.isfinite(power)
  202. or lt_r2 < 0.4
  203. ):
  204. slope = uf_state_default.slope
  205. power = uf_state_default.power
  206. return {
  207. "R_end": R_end,
  208. "nuK": float(nuK),
  209. "slope": float(slope),
  210. "power": float(power),
  211. }
  212. # ======================================================================
  213. # 当前周期初始进水段分析
  214. # ======================================================================
  215. def _analyze_init_cycle_csv(
  216. self,
  217. df,
  218. unit_name,
  219. uf_state_default,
  220. state_bounds
  221. ) -> Dict[str, float]:
  222. """
  223. 当前周期初始进水段分析
  224. """
  225. flow_col = self.flow_format.format(unit=unit_name)
  226. tmp_col = self.tmp_format.format(unit=unit_name)
  227. temp_col = self.temp_col
  228. res_col = f"{unit_name}_R_scaled"
  229. segments = [df]
  230. segments = self.res_calc.calculate_for_segments(
  231. segments,
  232. temp_col=self.temp_col,
  233. flow_col=flow_col,
  234. tmp_col=tmp_col,
  235. )
  236. df = segments[-1]
  237. return {
  238. "q_mean": float(df[flow_col].mean()),
  239. "tmp_mean": float(df[tmp_col].mean()),
  240. "temp_mean": float(df[temp_col].mean()),
  241. "R_start": float(df[res_col].mean()),
  242. }
  243. def _correct_nuk_with_predict(
  244. self,
  245. df_predict,
  246. unit_name,
  247. R_start,
  248. q_mean,
  249. temp_celsius,
  250. base_nuk,
  251. uf_state_default,
  252. ):
  253. """
  254. 使用 predict_csv 中预测的渗透率,
  255. 对短期污染参数 nuK 进行在线修正。
  256. """
  257. per_col = self.per_format.format(unit=unit_name)
  258. if per_col not in df_predict.columns:
  259. return base_nuk
  260. per = pd.to_numeric(
  261. df_predict[per_col],
  262. errors="coerce"
  263. )
  264. mask = (
  265. np.isfinite(per)
  266. & (per > 0)
  267. )
  268. per = per[mask]
  269. if len(per) < 5:
  270. return base_nuk
  271. mu = self.res_calc.xishan_viscosity(temp_celsius)
  272. R = 3.6e11 / (mu * per)
  273. R_scaled = R / self.res_calc.scale_factor
  274. R_scaled = (R_scaled- R_scaled.iloc[0]+ R_start)
  275. t = np.arange(len(R_scaled)) * 60.0
  276. J_const = q_mean / self.res_calc.A / 3600.0
  277. if not np.isfinite(J_const) or J_const <= 0:
  278. return base_nuk
  279. x = J_const * t
  280. try:
  281. coef = np.polyfit(x, R_scaled, 1)
  282. predict_nuk = float(coef[0])
  283. pred = np.polyval(coef, x)
  284. r2 = r2_score(R_scaled, pred)
  285. except Exception:
  286. return base_nuk
  287. if (
  288. not np.isfinite(r2)
  289. or not np.isfinite(predict_nuk)
  290. or predict_nuk <= 0
  291. or r2 < 0.4
  292. ):
  293. return base_nuk
  294. corrected_nuk = (
  295. 0.7 * base_nuk
  296. + 0.3 * predict_nuk
  297. )
  298. if (
  299. not np.isfinite(corrected_nuk)
  300. or corrected_nuk <= 0
  301. ):
  302. return uf_state_default.nuK
  303. return float(corrected_nuk)