SDHU_AB.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 = {'x':np.array([1])},
  145. train_metric = {'R2':1,'MAE':1,'MAPE':1}
  146. )
  147. self.TVP_data = self.get_TVP(self.param_posterior,observed_data)
  148. self.TVP_metric = self.get_metric(self.TVP_data)
  149. if plot_TVP:
  150. self.plot_TVP(self.TVP_data).show()
  151. return self
  152. @property
  153. def F_air_val_rw(self):
  154. return None
  155. def set_F_air_val_rw(self,value:float):
  156. return self
  157. def clean_data(
  158. self,
  159. data : pd.DataFrame,
  160. data_type : list=['input','observed'],
  161. print_process: bool = True,
  162. fill_zero : bool = False,
  163. save_log : Union[str,None] = None
  164. ) -> pd.DataFrame:
  165. data = data.replace(-9999,np.nan)
  166. clean_data = DataCleaner(data,print_process=print_process)
  167. if 'input' in data_type:
  168. clean_data = (
  169. clean_data
  170. .rm_rolling_fluct(window=60,fun='ptp',thre=0.1,include_cols=['State'])
  171. .rm_rule('State != 1')
  172. .rm_rule('fan_1_Hz < 10').rm_rule('fan_2_Hz < 10')
  173. .rm_outrange(method='raw',upper=140,lower=20,include_cols=['wheel_1_TinR'])
  174. )
  175. if 'observed' in data_type:
  176. pass
  177. clean_data = clean_data.get_data(
  178. fill = 0 if fill_zero else None,
  179. save_log = save_log
  180. )
  181. return clean_data
  182. # def optimize(
  183. # self,
  184. # cur_input_data: pd.DataFrame,
  185. # wheel_1_TinR : tuple = (70,120),
  186. # wheel_2_TinR : tuple = (70,120),
  187. # fan_2_Hz : tuple = (30,50),
  188. # constrains : list = None,
  189. # logging : bool = True,
  190. # target : str = 'summary_Fs',
  191. # target_min : bool = True
  192. # ) -> list:
  193. # constrains = [] if constrains is None else constrains
  194. # cur_input_data = cur_input_data.iloc[[0],:]
  195. # opt_var_boundary = {}
  196. # if wheel_1_TinR is not None:
  197. # opt_var_boundary['wheel_1_TinR'] = {'lb':min(wheel_1_TinR),'ub':max(wheel_1_TinR)}
  198. # if wheel_2_TinR is not None:
  199. # opt_var_boundary['wheel_2_TinR'] = {'lb':min(wheel_2_TinR),'ub':max(wheel_2_TinR)}
  200. # if fan_2_Hz is not None:
  201. # opt_var_boundary['fan_2_Hz'] = {'lb':min(fan_2_Hz),'ub':max(fan_2_Hz)}
  202. # opt_var_value = cur_input_data.loc[:,list(opt_var_boundary.keys())]
  203. # oth_var_value = (
  204. # cur_input_data
  205. # .loc[:,list(self.model_input_data_columns.values())]
  206. # .drop(opt_var_value.columns,axis=1)
  207. # )
  208. # opt_res = optimizer(
  209. # model = self,
  210. # opt_var_boundary = opt_var_boundary,
  211. # opt_var_value = opt_var_value,
  212. # oth_var_value = oth_var_value,
  213. # target = target,
  214. # target_min = target_min,
  215. # constrains = constrains,
  216. # logging = logging,
  217. # other_kwargs = {'NIND':2000,'MAXGEN':50}
  218. # )
  219. # return opt_res
  220. # def plot_opt(
  221. # self,
  222. # cur_input_data: pd.DataFrame,
  223. # target_min : str = 'summary_waste',
  224. # ):
  225. # data_input = (
  226. # pd.MultiIndex.from_product(
  227. # [
  228. # np.linspace(70,120,1000),
  229. # np.linspace(70,120,1000),
  230. # ],
  231. # names=['wheel_1_TinR','wheel_2_TinR']
  232. # )
  233. # .to_frame(index=False)
  234. # )
  235. # for col in cur_input_data.columns:
  236. # if col in data_input.columns:
  237. # continue
  238. # data_input[col] = cur_input_data.loc[:,col].iat[0]
  239. # data_output = self.predict_system(data_input)
  240. # data = (
  241. # data_output
  242. # .assign(
  243. # wheel_1_TinR = data_input.loc[:,'wheel_1_TinR'],
  244. # wheel_2_TinR = data_input.loc[:,'wheel_2_TinR'],
  245. # )
  246. # .assign(coil_3_DoutA=lambda dt:dt.coil_3_DoutA.round(1))
  247. # .loc[lambda dt:dt.groupby('coil_3_DoutA')[target_min].idxmin()]
  248. # .loc[lambda dt:dt.coil_3_DoutA.mod(1)==0]
  249. # )
  250. # import plotnine as gg
  251. # plot = (
  252. # data
  253. # .pipe(gg.ggplot)
  254. # + gg.aes(x='wheel_1_TinR',y='wheel_2_TinR')
  255. # + gg.geom_path(size=1)
  256. # + gg.geom_point()
  257. # + gg.geom_label(gg.aes(label='coil_3_DoutA'))
  258. # + gg.geom_abline(slope=1,intercept=0,color='red',linetype='--')
  259. # )
  260. # return plot
  261. # def plot_check(self,cur_input_data:pd.DataFrame) -> dict:
  262. # pa1=self.curve(input_data=cur_input_data,x='wheel_1_TinR',y='wheel_1_DoutP')
  263. # pa2=self.curve(input_data=cur_input_data,x='wheel_1_TinR',y='wheel_1_ToutP')
  264. # pa3=self.curve(input_data=cur_input_data,x='wheel_1_TinR',y='wheel_1_EFF')
  265. # pb1=self.curve(input_data=cur_input_data,x='wheel_2_TinR',y='wheel_2_DoutP')
  266. # pb2=self.curve(input_data=cur_input_data,x='wheel_2_TinR',y='wheel_2_ToutP')
  267. # pb3=self.curve(input_data=cur_input_data,x='wheel_2_TinR',y='wheel_2_EFF')
  268. # plot1 = (pa1|pa2|pa3)/(pb1|pb2|pb3)
  269. # return {'plot1':plot1}
  270. def model_A(
  271. Tin_F, # 前表冷后温度
  272. Hin_F, # 前表冷后湿度
  273. coil_1_ToutA,
  274. coil_1_HoutA,
  275. fan_1_Hz, # 处理侧风机频率
  276. fan_2_Hz, # 再生侧风机频率
  277. coil_2_TinW, # 中表冷进水温度
  278. coil_2_Val, # 中表冷阀门开度
  279. wheel_1_TinR, # 前转轮再生侧温度
  280. engine : str,
  281. components: dict,
  282. param : dict,
  283. mixed_1_TinM = 0, # 回风温度(处理侧)
  284. mixed_1_HinM = 0, # 回风湿度(处理侧)
  285. ) -> dict:
  286. # 水的质量流量
  287. coil_2_FW = coil_2_Val / 100
  288. # 空气的质量流量
  289. air_flow = AirFlow_SDHU_A.model(fan_1_Hz=fan_1_Hz,fan_2_Hz=fan_2_Hz,param=param)
  290. # 前转轮
  291. wheel_1_res = components['wheel_1'].model(
  292. TinP = coil_1_ToutA,
  293. HinP = coil_1_HoutA,
  294. FP = air_flow['wheel_1_FaP'],
  295. TinR = wheel_1_TinR,
  296. HinR = 0,
  297. FR = air_flow['wheel_1_FaR'],
  298. TinC = Tin_F,
  299. HinC = Hin_F,
  300. FC = air_flow['wheel_1_FaC'],
  301. engine = engine,
  302. param = param['wheel_1']
  303. )
  304. # 处理侧混风(回风)
  305. mixed_1_res = components['mixed_1'].model(
  306. TinA = wheel_1_res['ToutP'],
  307. HinA = wheel_1_res['HoutP'],
  308. FA = air_flow['mixed_1_FaA'],
  309. TinM = mixed_1_TinM,
  310. HinM = mixed_1_HinM,
  311. FM = air_flow['mixed_1_FaM'],
  312. engine = engine
  313. )
  314. # 中表冷
  315. coil_2_res = components['coil_2'].model(
  316. TinA = mixed_1_res['ToutA'],
  317. HinA = mixed_1_res['HoutA'],
  318. FA = air_flow['coil_2_FaA'],
  319. TinW = coil_2_TinW,
  320. FW = coil_2_FW,
  321. engine = engine,
  322. param = param['coil_2']
  323. )
  324. # 后转轮湿度修正
  325. wheel_1_res_adj = components['wheel_1'].model(
  326. TinP = coil_1_ToutA,
  327. HinP = coil_1_HoutA,
  328. FP = air_flow['wheel_1_FaP'],
  329. TinR = wheel_1_TinR,
  330. HinR = wheel_1_res['HoutC'],
  331. FR = air_flow['wheel_1_FaR'],
  332. TinC = Tin_F,
  333. HinC = Hin_F,
  334. FC = air_flow['wheel_1_FaC'],
  335. engine = engine,
  336. param = param['wheel_1']
  337. )
  338. # 前再生加热盘管
  339. heatingcoil_1_res = components['heatingcoil_1'].model(
  340. TinA = wheel_1_res_adj['ToutC'],
  341. ToutA = wheel_1_TinR,
  342. FA = air_flow['heatingcoil_1_Fa'],
  343. param = param['heatingcoil_1'],
  344. engine = engine
  345. )
  346. # waste = cal_Q_waste(
  347. # wheel_1_res = wheel_1_res_adj,
  348. # wheel_2_res = wheel_2_res_adj,
  349. # heatingcoil_1_res = heatingcoil_1_res,
  350. # heatingcoil_2_res = heatingcoil_2_res,
  351. # wheel_1_TinR = wheel_1_TinR,
  352. # wheel_2_TinR = wheel_2_TinR
  353. # )
  354. return {
  355. 'coil_2' : coil_2_res,
  356. 'wheel_1' : wheel_1_res_adj,
  357. 'mixed_1' : mixed_1_res,
  358. 'heatingcoil_1': heatingcoil_1_res,
  359. 'Fa' : air_flow,
  360. 'summary' : {
  361. 'Fs' : heatingcoil_1_res['Fs'],
  362. # **waste,
  363. }
  364. }
  365. class AirFlow_SDHU_A:
  366. @classmethod
  367. def model(cls,fan_1_Hz,fan_2_Hz,param):
  368. F_air_X2_base = 1 # 进入转轮处理侧的新风量
  369. F_air_H_base = param['F_air'].get('H_base',0)
  370. F_air_P_base = param['F_air']['P_base']
  371. Fa_H = F_air_H_base + (fan_1_Hz/50) * param['F_air'].get('HzP_H',0)
  372. Fa_X2 = F_air_X2_base + (fan_1_Hz/50) * param['F_air']['HzP_X2']
  373. Fa_S = Fa_H + Fa_X2
  374. Fa_P = F_air_P_base + (fan_2_Hz/50) * param['F_air']['HzR_P']
  375. return {
  376. 'wheel_1_FaP' : Fa_X2,
  377. 'wheel_1_FaC' : Fa_P,
  378. 'wheel_1_FaR' : Fa_P,
  379. 'coil_2_FaA' : Fa_S,
  380. 'mixed_1_FaM' : Fa_H,
  381. 'mixed_1_FaA' : Fa_X2,
  382. 'heatingcoil_1_Fa': Fa_P
  383. }
  384. @classmethod
  385. def prior(cls,exist_Fa_H):
  386. param = {}
  387. param['HzP_X2'] = pm.HalfNormal('F_air_HzP_X2',sigma=1,initval=0.5)
  388. param['HzR_P'] = pm.HalfNormal('F_air_HzR_P',sigma=1,initval=0.5)
  389. param['P_base'] = pm.TruncatedNormal('F_air_P_base',mu=1,sigma=0.2,lower=0,initval=1)
  390. if exist_Fa_H:
  391. param['H_base'] = pm.TruncatedNormal('F_air_H_base',mu=1,sigma=0.2,lower=0,initval=1)
  392. param['HzP_H'] = pm.HalfNormal('F_air_HzP_H',sigma=1,initval=0.5)
  393. return param
  394. def cal_Q_waste(
  395. wheel_1_res,
  396. wheel_2_res,
  397. heatingcoil_1_res,
  398. heatingcoil_2_res,
  399. wheel_1_TinR,
  400. wheel_2_TinR
  401. ):
  402. waste_Qsen1 = wheel_1_res['Qsen']
  403. waste_Qsen2 = wheel_2_res['Qsen']
  404. waste_cond1 = heatingcoil_1_res['Q'] * (0.15 + 0.0001 * (wheel_1_TinR-70)**2)
  405. waste_cond2 = heatingcoil_2_res['Q'] * (0.15 + 0.0001 * (wheel_2_TinR-70)**2)
  406. waste_out = (
  407. heatingcoil_1_res['Q'] + heatingcoil_2_res['Q']
  408. - wheel_1_res['Qsen'] - wheel_1_res['Qlat']
  409. - wheel_2_res['Qsen'] - wheel_2_res['Qlat']
  410. )
  411. return {
  412. 'waste_Qsen1': waste_Qsen1,
  413. 'waste_Qsen2': waste_Qsen2,
  414. 'waste_Qout' : waste_out,
  415. 'waste_cond1': waste_cond1,
  416. 'waste_cond2': waste_cond2,
  417. 'waste_out' : waste_out,
  418. 'waste' : waste_Qsen1+waste_cond2+waste_cond1+waste_cond2+waste_out,
  419. }