health_evalution_class.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import numpy as np
  2. import pandas as pd
  3. from sklearn.neighbors import BallTree
  4. from typing import Dict, List, Optional, Union
  5. from functools import lru_cache
  6. class HealthAssessor:
  7. def __init__(self):
  8. self.subsystem_config = {
  9. # 发电机
  10. 'generator': {
  11. # 双馈
  12. 'dfig': {
  13. 'fixed': ['generator_winding1_temperature', 'generator_winding2_temperature',
  14. 'generator_winding3_temperature', 'generatordrive_end_bearing_temperature',
  15. 'generatornon_drive_end_bearing_temperature'],
  16. },
  17. # 直驱
  18. 'direct': {
  19. 'fixed': ['generator_winding1_temperature', 'generator_winding2_temperature',
  20. 'generator_winding3_temperature', 'main_bearing_temperature'],
  21. }
  22. },
  23. # 机舱系统
  24. 'nacelle': {
  25. 'fixed': ['front_back_vibration_of_the_cabin', 'side_to_side_vibration_of_the_cabin',
  26. 'cabin_position', 'cabin_temperature'],
  27. },
  28. # 电网环境
  29. 'grid': {
  30. 'fixed': ['reactive_power', 'active_power', 'grid_a_phase_current',
  31. 'grid_b_phase_current', 'grid_c_phase_current'],
  32. },
  33. # 传动系统
  34. 'drive_train': {
  35. 'fixed': ['main_bearing_temperature'],
  36. 'keywords': [
  37. {'include': ['gearbox', 'temperature'], 'exclude': [], 'min_count': 2},
  38. ]
  39. }
  40. }
  41. # 嵌入源代码的MSET实现
  42. self.mset = self._create_mset_core()
  43. def _create_mset_core(self):
  44. """创建MSET核心计算模块"""
  45. class MSETCore:
  46. def __init__(self):
  47. self.matrixD = None
  48. self.normalDataBallTree = None
  49. self.healthyResidual = None
  50. def calcSimilarity(self, x, y):
  51. """优化后的相似度计算"""
  52. diff = np.array(x) - np.array(y)
  53. return 1 / (1 + np.sqrt(np.sum(diff ** 2)))
  54. def genDLMatrix(self, trainDataset, dataSize4D=15, dataSize4L=5):
  55. """优化矩阵生成过程"""
  56. m, n = trainDataset.shape
  57. # 快速选择极值点
  58. min_indices = np.argmin(trainDataset, axis=0)
  59. max_indices = np.argmax(trainDataset, axis=0)
  60. unique_indices = np.unique(np.concatenate([min_indices, max_indices]))
  61. self.matrixD = trainDataset[unique_indices].copy()
  62. # 快速填充剩余点
  63. remaining_indices = np.setdiff1d(np.arange(m), unique_indices)
  64. np.random.shuffle(remaining_indices)
  65. needed = max(0, dataSize4D - len(unique_indices))
  66. if needed > 0:
  67. self.matrixD = np.vstack([self.matrixD, trainDataset[remaining_indices[:needed]]])
  68. # 使用与源代码一致的BallTree参数
  69. self.normalDataBallTree = BallTree(
  70. self.matrixD,
  71. leaf_size=40,
  72. metric=lambda i, j: 1 - self.calcSimilarity(i, j) # 自定义相似度
  73. )
  74. # 使用所有数据计算残差
  75. self.healthyResidual = self.calcResidualByLocallyWeightedLR(trainDataset)
  76. return 0
  77. def calcResidualByLocallyWeightedLR(self, newStates):
  78. """优化残差计算"""
  79. if len(newStates.shape) == 1:
  80. newStates = newStates.reshape(-1, 1)
  81. dist, iList = self.normalDataBallTree.query(
  82. newStates,
  83. k=min(10, len(self.matrixD)),
  84. return_distance=True
  85. )
  86. weights = 1 / (dist + 1e-5)
  87. weights /= weights.sum(axis=1)[:, np.newaxis]
  88. est_X = np.sum(weights[:, :, np.newaxis] * self.matrixD[iList[0]], axis=1)
  89. return est_X - newStates
  90. def calcSPRT(self, newsStates, feature_weight, alpha=0.1, beta=0.1, decisionGroup=1):
  91. """优化SPRT计算"""
  92. stateResidual = self.calcResidualByLocallyWeightedLR(newsStates)
  93. weightedStateResidual = np.dot(stateResidual, feature_weight)
  94. weightedHealthyResidual = np.dot(self.healthyResidual, feature_weight)
  95. mu0 = np.mean(weightedHealthyResidual)
  96. sigma0 = np.std(weightedHealthyResidual)
  97. # 向量化计算
  98. n = len(newsStates)
  99. if n < decisionGroup:
  100. return [50] # 中性值
  101. rolling_mean = np.convolve(weightedStateResidual, np.ones(decisionGroup) / decisionGroup, 'valid')
  102. si = (rolling_mean - mu0) * (rolling_mean + mu0 - 2 * mu0) / (2 * sigma0 ** 2)
  103. lowThres = np.log(beta / (1 - alpha))
  104. highThres = np.log((1 - beta) / alpha)
  105. si = np.clip(si, lowThres, highThres)
  106. si = np.where(si > 0, si / highThres, si / lowThres)
  107. flag = 100 - si * 100
  108. # 填充不足的部分
  109. if len(flag) < n:
  110. flag = np.pad(flag, (0, n - len(flag)), mode='edge')
  111. return flag.tolist()
  112. def CRITIC_prepare(self, data, flag=1):
  113. """标准化处理"""
  114. data = data.astype(float)
  115. numeric_cols = data.select_dtypes(include=[np.number]).columns
  116. negative_cols = [col for col in numeric_cols
  117. if any(kw in col for kw in ['temperature'])]
  118. positive_cols = list(set(numeric_cols) - set(negative_cols))
  119. # 负向标准化
  120. if negative_cols:
  121. max_val = data[negative_cols].max()
  122. min_val = data[negative_cols].min()
  123. data[negative_cols] = (max_val - data[negative_cols]) / (max_val - min_val).replace(0, 1e-5)
  124. # 正向标准化
  125. if positive_cols:
  126. max_val = data[positive_cols].max()
  127. min_val = data[positive_cols].min()
  128. data[positive_cols] = (data[positive_cols] - min_val) / (max_val - min_val).replace(0, 1e-5)
  129. return data
  130. def CRITIC(self, data):
  131. """CRITIC权重计算(支持单特征)"""
  132. try:
  133. # 处理单特征情况
  134. if len(data.columns) == 1:
  135. return pd.Series([1.0], index=data.columns)
  136. data_norm = self.CRITIC_prepare(data.copy())
  137. std = data_norm.std(ddof=0).clip(lower=0.01)
  138. # 计算相关系数矩阵(添加异常处理)
  139. try:
  140. corr = np.abs(np.corrcoef(data_norm.T))
  141. np.fill_diagonal(corr, 0)
  142. conflict = np.sum(1 - corr, axis=1)
  143. except:
  144. # 如果计算相关系数失败,使用等权重
  145. return pd.Series(np.ones(len(data.columns))/len(data.columns))
  146. info = std * conflict
  147. weights = info / info.sum()
  148. return pd.Series(weights, index=data.columns)
  149. except Exception as e:
  150. print(f"CRITIC计算失败: {str(e)}")
  151. return pd.Series(np.ones(len(data.columns))/len(data.columns))
  152. def ahp(self, matrix):
  153. """AHP权重计算"""
  154. eigenvalue, eigenvector = np.linalg.eig(matrix)
  155. max_idx = np.argmax(eigenvalue)
  156. weight = eigenvector[:, max_idx].real
  157. return weight / weight.sum(), eigenvalue[max_idx].real
  158. return MSETCore()
  159. def assess_turbine(self, engine_code, data, mill_type, wind_turbine_name):
  160. """评估单个风机"""
  161. results = {
  162. "engine_code": engine_code,
  163. "wind_turbine_name": wind_turbine_name,
  164. "mill_type": mill_type,
  165. "total_health_score": None,
  166. "subsystems": {},
  167. "assessed_subsystems": []
  168. }
  169. # 各子系统评估
  170. subsystems_to_assess = [
  171. ('generator', self.subsystem_config['generator'][mill_type], 1),
  172. ('nacelle', self.subsystem_config['nacelle'], 1),
  173. ('grid', self.subsystem_config['grid'], 1),
  174. ('drive_train', self.subsystem_config['drive_train'] if mill_type == 'dfig' else None, 1)
  175. ]
  176. for subsystem, config, min_features in subsystems_to_assess:
  177. if config is None:
  178. continue
  179. features = self._get_subsystem_features(config, data)
  180. # 功能1:无论特征数量是否足够都输出结果
  181. if len(features) >= min_features:
  182. assessment = self._assess_subsystem(data[features])
  183. else:
  184. assessment = {
  185. 'health_score': -1, # 特征不足时输出'-'
  186. 'weights': {},
  187. 'message': f'Insufficient features (required {min_features}, got {len(features)})'
  188. }
  189. print('结果打印',assessment)
  190. # 功能3:删除features内容
  191. if 'features' in assessment:
  192. del assessment['features']
  193. # 最终清理:确保没有NaN值
  194. for sys, result in results["subsystems"].items():
  195. if isinstance(result['health_score'], float) and np.isnan(result['health_score']):
  196. result['health_score'] = -1
  197. result['message'] = (result.get('message') or '') + '; NaN detected'
  198. if isinstance(results["total_health_score"], float) and np.isnan(results["total_health_score"]):
  199. results["total_health_score"] = -1
  200. results["subsystems"][subsystem] = assessment
  201. # 计算整机健康度(使用新字段名)
  202. if results["subsystems"]:
  203. # 只计算健康值为数字的子系统
  204. valid_subsystems = [
  205. k for k, v in results["subsystems"].items()
  206. if isinstance(v['health_score'], (int, float)) and v['health_score'] >= 0
  207. ]
  208. if valid_subsystems:
  209. weights = self._get_subsystem_weights(valid_subsystems)
  210. health_scores = [results["subsystems"][sys]['health_score'] for sys in valid_subsystems]
  211. results["total_health_score"] = float(np.dot(health_scores, weights))
  212. results["assessed_subsystems"] = valid_subsystems
  213. return results
  214. def _get_all_possible_features(self, mill_type, available_columns):
  215. """
  216. 获取所有可能的特征列(基于实际存在的列)
  217. 参数:
  218. mill_type: 机型类型
  219. available_columns: 数据库实际存在的列名列表
  220. """
  221. features = []
  222. available_columns_lower = [col.lower() for col in available_columns] # 不区分大小写匹配
  223. # for subsys_name, subsys_config in assessor.subsystem_config.items():
  224. for subsys_name, subsys_config in self.subsystem_config.items():
  225. # 处理子系统配置
  226. if subsys_name == 'generator':
  227. config = subsys_config.get(mill_type, {})
  228. elif subsys_name == 'drive_train' and mill_type != 'dfig':
  229. continue
  230. else:
  231. config = subsys_config
  232. # 处理固定特征
  233. if 'fixed' in config:
  234. for f in config['fixed']:
  235. if f in available_columns:
  236. features.append(f)
  237. # 处理关键词特征
  238. if 'keywords' in config:
  239. for rule in config['keywords']:
  240. matched = []
  241. include_kws = [kw.lower() for kw in rule['include']]
  242. exclude_kws = [ex.lower() for ex in rule.get('exclude', [])]
  243. for col in available_columns:
  244. col_lower = col.lower()
  245. # 检查包含关键词
  246. include_ok = all(kw in col_lower for kw in include_kws)
  247. # 检查排除关键词
  248. exclude_ok = not any(ex in col_lower for ex in exclude_kws)
  249. if include_ok and exclude_ok:
  250. matched.append(col)
  251. if len(matched) >= rule.get('min_count', 1):
  252. features.extend(matched)
  253. return list(set(features)) # 去重
  254. def _get_subsystem_features(self, config: Dict, data: pd.DataFrame) -> List[str]:
  255. """最终版特征获取方法"""
  256. available_features = []
  257. # 固定特征检查(要求至少10%非空)
  258. if 'fixed' in config:
  259. for f in config['fixed']:
  260. if f in data.columns and data[f].notna().mean() > 0.1:
  261. available_features.append(f)
  262. print(f"匹配到的固定特征: {available_features}")
  263. # 关键词特征检查
  264. if 'keywords' in config:
  265. for rule in config['keywords']:
  266. matched = [
  267. col for col in data.columns
  268. if all(kw.lower() in col.lower() for kw in rule['include'])
  269. and not any(ex.lower() in col.lower() for ex in rule.get('exclude', []))
  270. and data[col].notna().mean() > 0.1 # 数据有效性检查
  271. ]
  272. if len(matched) >= rule.get('min_count', 1):
  273. available_features.extend(matched)
  274. print(f"匹配到的关键词特征: {available_features}")
  275. return list(set(available_features))
  276. def _assess_subsystem(self, data: pd.DataFrame) -> Dict:
  277. """评估子系统(支持单特征)"""
  278. # 数据清洗
  279. clean_data = data.dropna()
  280. if len(clean_data) < 10: # 降低最小样本量要求(原为20)
  281. return {'health_score': -1, 'weights': {}, 'features': list(data.columns), 'message': 'Insufficient data'}
  282. try:
  283. # 标准化
  284. normalized_data = self.mset.CRITIC_prepare(clean_data)
  285. # 计算权重 - 处理单特征情况
  286. if len(normalized_data.columns) == 1:
  287. weights = pd.Series([1.0], index=normalized_data.columns)
  288. else:
  289. weights = self.mset.CRITIC(normalized_data)
  290. # MSET评估
  291. health_score = self._run_mset_assessment(normalized_data.values, weights.values)
  292. bins = [0, 10, 20, 30, 40, 50, 60, 70, 80]
  293. adjust_values = [87, 77, 67, 57, 47, 37, 27, 17, 7]
  294. def adjust_score(score):
  295. for i in range(len(bins)):
  296. if score < bins[i]:
  297. return score + adjust_values[i-1]
  298. return score #
  299. adjusted_score = adjust_score(health_score) #
  300. if adjusted_score >= 100:
  301. adjusted_score = 92.8
  302. return {
  303. 'health_score': float(health_score),
  304. 'weights': weights.to_dict(),
  305. 'features': list(data.columns)
  306. }
  307. except Exception as e:
  308. return {'health_score': -1, 'weights': {}, 'features': list(data.columns), 'message': str(e)}
  309. @lru_cache(maxsize=10)
  310. def _get_mset_model(self, train_data: tuple):
  311. """缓存MSET模型"""
  312. # 注意:由于lru_cache需要可哈希参数,这里使用元组
  313. arr = np.array(train_data)
  314. model = self._create_mset_core()
  315. model.genDLMatrix(arr)
  316. return model
  317. def _run_mset_assessment(self, data: np.ndarray, weights: np.ndarray) -> float:
  318. """执行MSET评估"""
  319. # 检查权重有效性
  320. if np.isnan(weights).any() or np.isinf(weights).any():
  321. weights = np.ones_like(weights) / len(weights) # 重置为等权重
  322. # 分割训练集和测试集
  323. split_idx = len(data) // 2
  324. train_data = data[:split_idx]
  325. test_data = data[split_idx:]
  326. # 使用缓存模型
  327. try:
  328. model = self._get_mset_model(tuple(map(tuple, train_data)))
  329. flags = model.calcSPRT(test_data, weights)
  330. # 过滤NaN值并计算均值
  331. valid_flags = [x for x in flags if not np.isnan(x)]
  332. if not valid_flags:
  333. return 50.0 # 默认中性值
  334. return float(np.mean(valid_flags))
  335. except Exception as e:
  336. print(f"MSET评估失败: {str(e)}")
  337. return 50.0 # 默认中性值
  338. def _get_subsystem_weights(self, subsystems: List[str]) -> np.ndarray:
  339. """生成等权重的子系统权重向量"""
  340. n = len(subsystems)
  341. if n == 0:
  342. return np.array([])
  343. # 直接返回等权重向量
  344. return np.ones(n) / n