SDHU_AB.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. from typing import Union
  2. import numpy as np
  3. import pandas as pd
  4. import pymc as pm
  5. import pytensor.tensor as pt
  6. from .._base._base_device import BaseDevice
  7. from ...components import (
  8. coil_water,coil_steam,wheel2,wheel3,mixed
  9. )
  10. from ..utils.fit_utils import (
  11. observe,reorder_posterior
  12. )
  13. from ...tools.optimizer import optimizer
  14. from ...tools.data_cleaner import DataCleaner
  15. class SDHU_AB(BaseDevice):
  16. val_rw_adj_target = ('coil_3_ToutA','coil_3_DoutA')
  17. def __init__(
  18. self,
  19. DHU_type = 'A',
  20. exist_Fa_H = True,
  21. wheel_1 = None,
  22. coolingcoil_2 = 'CoolingCoil2',
  23. heatingcoil_1 = 'SteamCoil',
  24. mixed_1 = 'Mixed',
  25. mixed_2 = 'Mixed',
  26. other_info = None
  27. ) -> None:
  28. super().__init__()
  29. self.DHU_type = DHU_type.replace('SDHU_','')
  30. if self.DHU_type == 'A':
  31. wheel_1 = wheel_1 if wheel_1 is not None else 'WheelS3V3'
  32. elif self.DHU_type == 'B':
  33. wheel_1 = wheel_1 if wheel_1 is not None else 'WheelS2V2'
  34. else:
  35. raise Exception('SDHU_type must be A or B')
  36. self.components_str = {
  37. 'wheel_1' : wheel_1,
  38. 'coil_2' : coolingcoil_2,
  39. 'heatingcoil_1': heatingcoil_1,
  40. 'mixed_1' : mixed_1,
  41. 'mixed_2' : mixed_2
  42. }
  43. self.exist_Fa_H = exist_Fa_H
  44. self.other_info = other_info if other_info is not None else {}
  45. self.record_load_info(
  46. components_str = self.components_str,
  47. DHU_type = self.DHU_type,
  48. exist_Fa_H = self.exist_Fa_H,
  49. other_info = self.other_info
  50. )
  51. @property
  52. def components(self):
  53. comp_map = {
  54. 'WheelS2':wheel2,'WheelS3':wheel3,'CoolingCoil':coil_water,
  55. 'SteamCoil':coil_steam,'Mixed':mixed
  56. }
  57. output ={}
  58. for comp_name,comp_model in self.components_str.items():
  59. if comp_model == 'SteamCoilVal':
  60. output[comp_name] = coil_steam.SteamCoilVal(
  61. name = comp_name,
  62. Fs_rated = self.other_info[f'{comp_name}_Fs_rated']
  63. )
  64. continue
  65. for comp_map_k,comp_map_v in comp_map.items():
  66. if comp_model.startswith(comp_map_k):
  67. output[comp_name] = getattr(comp_map_v,comp_model)(name = comp_name)
  68. return output
  69. @property
  70. def model_input_data_columns(self):
  71. columns = {
  72. 'Tin_F' : 'coil_1_ToutA',
  73. 'Hin_F' : 'coil_1_HoutA',
  74. 'fan_1_Hz' : 'fan_1_Hz',
  75. 'fan_2_Hz' : 'fan_2_Hz',
  76. 'coil_2_TinW' : 'coil_2_TinW',
  77. 'coil_2_Val' : 'coil_2_Val',
  78. 'wheel_1_TinR': 'wheel_1_TinR',
  79. }
  80. if self.exist_Fa_H:
  81. columns['mixed_1_TinM'] = 'mixed_1_TinM'
  82. columns['mixed_1_HinM'] = 'mixed_1_HinM'
  83. if self.DHU_type == 'A':
  84. columns['coil_1_ToutA'] = 'coil_1_ToutA'
  85. columns['coil_1_HoutA'] = 'coil_1_HoutA'
  86. return columns
  87. @property
  88. def model_observe_data_columns(self):
  89. columns = {
  90. 'mixed_1_ToutA': 'mixed_1_ToutA',
  91. 'mixed_1_DoutA': 'mixed_1_DoutA',
  92. 'coil_2_ToutA' : 'coil_2_ToutA',
  93. 'coil_2_DoutA' : 'coil_2_DoutA',
  94. }
  95. if self.DHU_type == 'A':
  96. columns['wheel_1_ToutC'] = 'wheel_1_ToutC' # A类除湿机前转轮是三分转轮
  97. exclude_obs = self.other_info.get('exclude_obs',[])
  98. for col in exclude_obs:
  99. if col in columns:
  100. del columns[col]
  101. return columns
  102. def model(self,*args,**kwargs):
  103. if self.DHU_type == 'A':
  104. return model_A(*args,**kwargs)
  105. elif self.DHU_type == 'B':
  106. # return model_B(*args,**kwargs)
  107. pass
  108. else:
  109. raise ValueError('DHU_type must be A or B')
  110. def fit(
  111. self,
  112. input_data : pd.DataFrame,
  113. observed_data: pd.DataFrame,
  114. plot_TVP : bool = True,
  115. ):
  116. if len(input_data) < 30:
  117. raise Exception('数据量过少')
  118. with pm.Model() as self.MODEL_PYMC:
  119. param_prior = {name:comp.prior() for name,comp in self.components.items()}
  120. param_prior['F_air'] = AirFlow_SDHU_A.prior(exist_Fa_H = self.exist_Fa_H)
  121. res = self.model(
  122. **{k:input_data.loc[:,v].values for k,v in self.model_input_data_columns.items()},
  123. engine = 'pymc',
  124. components = self.components,
  125. param = param_prior
  126. )
  127. for std_name,name in self.model_observe_data_columns.items():
  128. if name not in observed_data.columns:
  129. raise Exception(f'Missing column: {name}')
  130. observed_data = observed_data.rename(columns={name:std_name})
  131. std_name_equp,std_name_point = std_name.rsplit('_',1)
  132. sigma = 1
  133. observe(
  134. name = std_name,
  135. var = res[std_name_equp][std_name_point],
  136. observed = observed_data,
  137. sigma = sigma
  138. )
  139. self.param_posterior = pm.find_MAP(maxeval=50000,include_transformed=False)
  140. self.record_load_info(param_posterior = self.param_posterior)
  141. self.record_model(
  142. model_name = 'ATD',
  143. model = reorder_posterior(param_prior,self.param_posterior),
  144. train_data = {
  145. 'wheel_1_TinR': observed_data.loc[:,'wheel_1_TinR'].values,
  146. 'fan_2_Hz' : observed_data.loc[:,'wheel_2_TinR'].values,
  147. 'coil_2_DoutA': observed_data.loc[:,'coil_2_DoutA'].values,
  148. },
  149. train_metric = {'R2':1,'MAE':1,'MAPE':1}
  150. )
  151. self.TVP_data = self.get_TVP(self.param_posterior,observed_data)
  152. self.TVP_metric = self.get_metric(self.TVP_data)
  153. if plot_TVP:
  154. self.plot_TVP(self.TVP_data).show()
  155. return self
  156. @property
  157. def F_air_val_rw(self):
  158. return None
  159. def set_F_air_val_rw(self,value:float):
  160. return self
  161. def clean_data(
  162. self,
  163. data : pd.DataFrame,
  164. data_type : list=['input','observed'],
  165. print_process: bool = True,
  166. fill_zero : bool = False,
  167. save_log : Union[str,None] = None
  168. ) -> pd.DataFrame:
  169. data = data.replace(-9999,np.nan)
  170. clean_data = DataCleaner(data,print_process=print_process)
  171. if 'input' in data_type:
  172. clean_data = (
  173. clean_data
  174. .rm_rolling_fluct(window=60,fun='ptp',thre=0.1,include_cols=['State'])
  175. .rm_rule('State != 1')
  176. .rm_rule('fan_1_Hz < 10').rm_rule('fan_2_Hz < 10')
  177. .rm_outrange(method='raw',upper=140,lower=20,include_cols=['wheel_1_TinR'])
  178. )
  179. if 'observed' in data_type:
  180. pass
  181. clean_data = clean_data.get_data(
  182. fill = 0 if fill_zero else None,
  183. save_log = save_log
  184. )
  185. return clean_data
  186. def optimize(
  187. self,
  188. cur_input_data: pd.DataFrame,
  189. wheel_1_TinR : tuple = (70,120),
  190. fan_2_Hz : tuple = (30,50),
  191. constrains : list = None,
  192. logging : bool = True,
  193. target : str = 'summary_Fs',
  194. target_min : bool = True
  195. ) -> list:
  196. constrains = [] if constrains is None else constrains
  197. cur_input_data = cur_input_data.iloc[[0],:]
  198. opt_var_boundary = {}
  199. if wheel_1_TinR is not None:
  200. opt_var_boundary['wheel_1_TinR'] = {'lb':min(wheel_1_TinR),'ub':max(wheel_1_TinR)}
  201. if fan_2_Hz is not None:
  202. opt_var_boundary['fan_2_Hz'] = {'lb':min(fan_2_Hz),'ub':max(fan_2_Hz)}
  203. opt_var_value = cur_input_data.loc[:,list(opt_var_boundary.keys())]
  204. oth_var_value = (
  205. cur_input_data
  206. .loc[:,list(set(self.model_input_data_columns.values()))]
  207. .drop(opt_var_value.columns,axis=1)
  208. )
  209. opt_res = optimizer(
  210. model = self,
  211. opt_var_boundary = opt_var_boundary,
  212. opt_var_value = opt_var_value,
  213. oth_var_value = oth_var_value,
  214. target = target,
  215. target_min = target_min,
  216. constrains = constrains,
  217. logging = logging,
  218. other_kwargs = {'NIND':2000,'MAXGEN':50}
  219. )
  220. return opt_res
  221. def plot_opt(
  222. self,
  223. cur_input_data: pd.DataFrame,
  224. target_min : str = 'summary_waste',
  225. coil_2_DoutA : tuple = None
  226. ):
  227. if coil_2_DoutA is None:
  228. coil_2_DoutA = (
  229. self.model_info['model_train_info_ATD']['coil_2_DoutA_min'],
  230. self.model_info['model_train_info_ATD']['coil_2_DoutA_max']
  231. )
  232. data_input = (
  233. pd.MultiIndex.from_product(
  234. [
  235. np.linspace(
  236. self.model_info['model_train_info_ATD']['wheel_1_TinR_min']-5,
  237. self.model_info['model_train_info_ATD']['wheel_1_TinR_max']+5,
  238. 1000
  239. ),
  240. np.linspace(
  241. self.model_info['model_train_info_ATD']['fan_2_Hz_min']-5,
  242. self.model_info['model_train_info_ATD']['fan_2_Hz_max']+5,
  243. 1000
  244. ),
  245. ],
  246. names=['wheel_1_TinR','fan_2_Hz']
  247. )
  248. .to_frame(index=False)
  249. )
  250. for col in cur_input_data.columns:
  251. if col in data_input.columns:
  252. continue
  253. data_input[col] = cur_input_data.loc[:,col].iat[0]
  254. data_output = self.predict_system(data_input)
  255. data = (
  256. data_output
  257. .assign(
  258. wheel_1_TinR = data_input.loc[:,'wheel_1_TinR'],
  259. fan_2_Hz = data_input.loc[:,'fan_2_Hz'],
  260. )
  261. .assign(coil_2_DoutA=lambda dt:dt.coil_2_DoutA.round(1))
  262. .loc[lambda dt:dt.coil_2_DoutA.between(*(min(coil_2_DoutA),max(coil_2_DoutA)))]
  263. .loc[lambda dt:dt.groupby('coil_2_DoutA')[target_min].idxmin()]
  264. .loc[lambda dt:dt.coil_2_DoutA.mod(0.5)==0]
  265. )
  266. import plotnine as gg
  267. plot = (
  268. data
  269. .pipe(gg.ggplot)
  270. + gg.aes(x='wheel_1_TinR',y='fan_2_Hz')
  271. + gg.geom_path(size=1)
  272. + gg.geom_point()
  273. + gg.geom_label(gg.aes(label='coil_2_DoutA'))
  274. + gg.geom_abline(slope=1,intercept=0,color='red',linetype='--')
  275. )
  276. return plot
  277. def plot_check(self,cur_input_data:pd.DataFrame) -> dict:
  278. pa1=self.curve(input_data=cur_input_data,x='wheel_1_TinR',y='wheel_1_DoutP')
  279. pa2=self.curve(input_data=cur_input_data,x='wheel_1_TinR',y='wheel_1_ToutP')
  280. pa3=self.curve(input_data=cur_input_data,x='wheel_1_TinR',y='wheel_1_EFF')
  281. pb1=self.curve(input_data=cur_input_data,x='fan_2_Hz',y='wheel_1_DoutP')
  282. pb2=self.curve(input_data=cur_input_data,x='fan_2_Hz',y='wheel_1_ToutP')
  283. pb3=self.curve(input_data=cur_input_data,x='fan_2_Hz',y='wheel_1_EFF')
  284. plot1 = (pa1|pa2|pa3)/(pb1|pb2|pb3)
  285. return {'plot1':plot1}
  286. def model_A(
  287. Tin_F, # 前表冷后温度
  288. Hin_F, # 前表冷后湿度
  289. coil_1_ToutA,
  290. coil_1_HoutA,
  291. fan_1_Hz, # 处理侧风机频率
  292. fan_2_Hz, # 再生侧风机频率
  293. coil_2_TinW, # 中表冷进水温度
  294. coil_2_Val, # 中表冷阀门开度
  295. wheel_1_TinR, # 前转轮再生侧温度
  296. engine : str,
  297. components: dict,
  298. param : dict,
  299. mixed_1_TinM = 0, # 回风温度(处理侧)
  300. mixed_1_HinM = 0, # 回风湿度(处理侧)
  301. ) -> dict:
  302. # 水的质量流量
  303. coil_2_FW = coil_2_Val / 100
  304. # 空气的质量流量
  305. air_flow = AirFlow_SDHU_A.model(fan_1_Hz=fan_1_Hz,fan_2_Hz=fan_2_Hz,param=param)
  306. # 前转轮
  307. wheel_1_res = components['wheel_1'].model(
  308. TinP = coil_1_ToutA,
  309. HinP = coil_1_HoutA,
  310. FP = air_flow['wheel_1_FaP'],
  311. TinR = wheel_1_TinR,
  312. HinR = 0,
  313. FR = air_flow['wheel_1_FaR'],
  314. TinC = Tin_F,
  315. HinC = Hin_F,
  316. FC = air_flow['wheel_1_FaC'],
  317. engine = engine,
  318. param = param['wheel_1']
  319. )
  320. # 处理侧混风(回风)
  321. mixed_1_res = components['mixed_1'].model(
  322. TinA = wheel_1_res['ToutP'],
  323. HinA = wheel_1_res['HoutP'],
  324. FA = air_flow['mixed_1_FaA'],
  325. TinM = mixed_1_TinM,
  326. HinM = mixed_1_HinM,
  327. FM = air_flow['mixed_1_FaM'],
  328. engine = engine
  329. )
  330. # 中表冷
  331. coil_2_res = components['coil_2'].model(
  332. TinA = mixed_1_res['ToutA'],
  333. HinA = mixed_1_res['HoutA'],
  334. FA = air_flow['coil_2_FaA'],
  335. TinW = coil_2_TinW,
  336. FW = coil_2_FW,
  337. engine = engine,
  338. param = param['coil_2']
  339. )
  340. # 后转轮湿度修正
  341. wheel_1_res_adj = components['wheel_1'].model(
  342. TinP = coil_1_ToutA,
  343. HinP = coil_1_HoutA,
  344. FP = air_flow['wheel_1_FaP'],
  345. TinR = wheel_1_TinR,
  346. HinR = wheel_1_res['HoutC'],
  347. FR = air_flow['wheel_1_FaR'],
  348. TinC = Tin_F,
  349. HinC = Hin_F,
  350. FC = air_flow['wheel_1_FaC'],
  351. engine = engine,
  352. param = param['wheel_1']
  353. )
  354. # 前再生加热盘管
  355. heatingcoil_1_res = components['heatingcoil_1'].model(
  356. TinA = wheel_1_res_adj['ToutC'],
  357. ToutA = wheel_1_TinR,
  358. FA = air_flow['heatingcoil_1_Fa'],
  359. param = param['heatingcoil_1'],
  360. engine = engine
  361. )
  362. waste = cal_Q_waste(
  363. wheel_1_res = wheel_1_res_adj,
  364. heatingcoil_1_res = heatingcoil_1_res,
  365. wheel_1_TinR = wheel_1_TinR,
  366. fan_2_Hz = fan_2_Hz
  367. )
  368. return {
  369. 'coil_2' : coil_2_res,
  370. 'wheel_1' : wheel_1_res_adj,
  371. 'mixed_1' : mixed_1_res,
  372. 'heatingcoil_1': heatingcoil_1_res,
  373. 'Fa' : air_flow,
  374. 'summary' : {
  375. 'Fs' : heatingcoil_1_res['Fs'],
  376. **waste,
  377. }
  378. }
  379. class AirFlow_SDHU_A:
  380. @classmethod
  381. def model(cls,fan_1_Hz,fan_2_Hz,param):
  382. F_air_X2_base = 1 # 进入转轮处理侧的新风量
  383. F_air_H_base = param['F_air'].get('H_base',0)
  384. F_air_P_base = param['F_air']['P_base']
  385. Fa_H = F_air_H_base + (fan_1_Hz/50) * param['F_air'].get('HzP_H',0)
  386. Fa_X2 = F_air_X2_base + (fan_1_Hz/50) * param['F_air']['HzP_X2']
  387. Fa_S = Fa_H + Fa_X2
  388. Fa_P = F_air_P_base + (fan_2_Hz/50) * param['F_air']['HzR_P']
  389. return {
  390. 'wheel_1_FaP' : Fa_X2,
  391. 'wheel_1_FaC' : Fa_P,
  392. 'wheel_1_FaR' : Fa_P,
  393. 'coil_2_FaA' : Fa_S,
  394. 'mixed_1_FaM' : Fa_H,
  395. 'mixed_1_FaA' : Fa_X2,
  396. 'heatingcoil_1_Fa': Fa_P
  397. }
  398. @classmethod
  399. def prior(cls,exist_Fa_H):
  400. param = {}
  401. param['HzP_X2'] = pm.HalfNormal('F_air_HzP_X2',sigma=1,initval=0.5)
  402. param['HzR_P'] = pm.HalfNormal('F_air_HzR_P',sigma=1,initval=0.5)
  403. param['P_base'] = pm.TruncatedNormal('F_air_P_base',mu=1,sigma=0.2,lower=0,initval=1)
  404. if exist_Fa_H:
  405. param['H_base'] = pm.TruncatedNormal('F_air_H_base',mu=1,sigma=0.2,lower=0,initval=1)
  406. param['HzP_H'] = pm.HalfNormal('F_air_HzP_H',sigma=1,initval=0.5)
  407. return param
  408. def cal_Q_waste(
  409. wheel_1_res,
  410. heatingcoil_1_res,
  411. wheel_1_TinR,
  412. fan_2_Hz
  413. ) -> dict:
  414. def waste_cond_func1(TinR):
  415. waste = 0.15 + 0.0001 * (TinR-70)**3
  416. return np.where(waste>0,waste,0)
  417. def waste_cond_func2(TinR):
  418. waste = 0.25 * (1 - np.exp(-0.04 * (TinR - 70)))
  419. return np.where(waste>0,waste,0)
  420. heatingcoil_1_Q = heatingcoil_1_res['Q']
  421. heatingcoil_1_Q = np.where(heatingcoil_1_Q>0,heatingcoil_1_Q,0)
  422. waste_Qsen1 = wheel_1_res['Qsen']
  423. waste_cond1 = heatingcoil_1_Q * waste_cond_func1(wheel_1_TinR)
  424. res = {
  425. 'waste_Qsen1': waste_Qsen1,
  426. 'waste_cond1': waste_cond1,
  427. }
  428. waste_out = heatingcoil_1_Q - wheel_1_res['Qsen'] - wheel_1_res['Qlat']
  429. waste_out = np.where(waste_out>0,waste_out,0)
  430. waste = waste_Qsen1 + waste_cond1 + waste_out + fan_2_Hz/100
  431. res['waste_out'] = waste_out
  432. res['waste'] = waste
  433. return res