health_evalution_class.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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=60, 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=4,
  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. #需要确认哪些指标是正向标准化 哪些是负向标准化
  117. negative_cols = [col for col in numeric_cols
  118. if any(kw in col for kw in ['temperature'])]
  119. positive_cols = list(set(numeric_cols) - set(negative_cols))
  120. # 负向标准化
  121. if negative_cols:
  122. max_val = data[negative_cols].max()
  123. min_val = data[negative_cols].min()
  124. data[negative_cols] = (max_val - data[negative_cols]) / (max_val - min_val).replace(0, 1e-5)
  125. # 正向标准化
  126. if positive_cols:
  127. max_val = data[positive_cols].max()
  128. min_val = data[positive_cols].min()
  129. data[positive_cols] = (data[positive_cols] - min_val) / (max_val - min_val).replace(0, 1e-5)
  130. return data
  131. def CRITIC(self, data):
  132. """CRITIC权重计算"""
  133. data_norm = self.CRITIC_prepare(data.copy())
  134. std = data_norm.std(ddof=0).clip(lower=0.01)
  135. corr = np.abs(np.corrcoef(data_norm.T))
  136. np.fill_diagonal(corr, 0)
  137. conflict = np.sum(1 - corr, axis=1)
  138. info = std * conflict
  139. weights = info / info.sum()
  140. return pd.Series(weights, index=data.columns)
  141. def ahp(self, matrix):
  142. """AHP权重计算"""
  143. eigenvalue, eigenvector = np.linalg.eig(matrix)
  144. max_idx = np.argmax(eigenvalue)
  145. weight = eigenvector[:, max_idx].real
  146. return weight / weight.sum(), eigenvalue[max_idx].real
  147. return MSETCore()
  148. def assess_turbine(self, engine_code, data, mill_type, wind_turbine_name):
  149. """评估单个风机
  150. """
  151. results = {
  152. "engine_code": engine_code,
  153. "wind_turbine_name": wind_turbine_name,
  154. "mill_type": mill_type,
  155. "total_health_score": None,
  156. "subsystems": {},
  157. "assessed_subsystems": []
  158. }
  159. # 各子系统评估
  160. subsystems_to_assess = [
  161. ('generator', self.subsystem_config['generator'][mill_type], 1),
  162. ('nacelle', self.subsystem_config['nacelle'],1),
  163. ('grid', self.subsystem_config['grid'], 1),
  164. ('drive_train', self.subsystem_config['drive_train'] if mill_type == 'dfig' else None,1)
  165. ]
  166. for subsystem, config, min_features in subsystems_to_assess:
  167. if config is None:
  168. continue
  169. features = self._get_subsystem_features(config, data)
  170. # 功能1:无论特征数量是否足够都输出结果
  171. if len(features) >= min_features:
  172. assessment = self._assess_subsystem(data[features])
  173. else:
  174. assessment = {
  175. 'health_score': -1, # 特征不足时输出'-'
  176. 'weights': {},
  177. 'message': f'Insufficient features (required {min_features}, got {len(features)})'
  178. }
  179. # 功能3:删除features内容
  180. if 'features' in assessment:
  181. del assessment['features']
  182. results["subsystems"][subsystem] = assessment
  183. # 计算整机健康度(使用新字段名)
  184. if results["subsystems"]:
  185. # 只计算健康值为数字的子系统
  186. valid_subsystems = [
  187. k for k, v in results["subsystems"].items()
  188. if isinstance(v['health_score'], (int, float)) and v['health_score'] >= 0
  189. ]
  190. if valid_subsystems:
  191. weights = self._get_subsystem_weights(valid_subsystems)
  192. health_scores = [results["subsystems"][sys]['health_score'] for sys in valid_subsystems]
  193. results["total_health_score"] = float(np.dot(health_scores, weights))
  194. results["assessed_subsystems"] = valid_subsystems
  195. return results
  196. def _get_all_possible_features(self,assessor, mill_type, available_columns):
  197. """
  198. 获取所有可能的特征列(基于实际存在的列)
  199. 参数:
  200. assessor: HealthAssessor实例
  201. mill_type: 机型类型
  202. available_columns: 数据库实际存在的列名列表
  203. """
  204. features = []
  205. available_columns_lower = [col.lower() for col in available_columns] # 不区分大小写匹配
  206. for subsys_name, subsys_config in assessor.subsystem_config.items():
  207. # 处理子系统配置
  208. if subsys_name == 'generator':
  209. config = subsys_config.get(mill_type, {})
  210. elif subsys_name == 'drive_train' and mill_type != 'dfig':
  211. continue
  212. else:
  213. config = subsys_config
  214. # 处理固定特征
  215. if 'fixed' in config:
  216. for f in config['fixed']:
  217. if f in available_columns:
  218. features.append(f)
  219. # 处理关键词特征
  220. if 'keywords' in config:
  221. for rule in config['keywords']:
  222. matched = []
  223. include_kws = [kw.lower() for kw in rule['include']]
  224. exclude_kws = [ex.lower() for ex in rule.get('exclude', [])]
  225. for col in available_columns:
  226. col_lower = col.lower()
  227. # 检查包含关键词
  228. include_ok = all(kw in col_lower for kw in include_kws)
  229. # 检查排除关键词
  230. exclude_ok = not any(ex in col_lower for ex in exclude_kws)
  231. if include_ok and exclude_ok:
  232. matched.append(col)
  233. if len(matched) >= rule.get('min_count', 1):
  234. features.extend(matched)
  235. return list(set(features)) # 去重
  236. def _get_subsystem_features(self, config: Dict, data: pd.DataFrame) -> List[str]:
  237. """最终版特征获取方法"""
  238. available_features = []
  239. # 固定特征检查(要求至少10%非空)
  240. if 'fixed' in config:
  241. for f in config['fixed']:
  242. if f in data.columns and data[f].notna().mean() > 0.1:
  243. available_features.append(f)
  244. print(f"匹配到的固定特征: {available_features}")
  245. # 关键词特征检查
  246. if 'keywords' in config:
  247. for rule in config['keywords']:
  248. matched = [
  249. col for col in data.columns
  250. if all(kw.lower() in col.lower() for kw in rule['include'])
  251. and not any(ex.lower() in col.lower() for ex in rule.get('exclude', []))
  252. and data[col].notna().mean() > 0.1 # 数据有效性检查
  253. ]
  254. if len(matched) >= rule.get('min_count', 1):
  255. available_features.extend(matched)
  256. print(f"匹配到的关键词特征: {available_features}")
  257. return list(set(available_features))
  258. def _assess_subsystem(self, data: pd.DataFrame) -> Dict:
  259. """评估子系统(与源代码逻辑完全一致)"""
  260. # 数据清洗
  261. clean_data = data.dropna()
  262. if len(clean_data) < 20: # 数据量不足
  263. return {'health_score': -1, 'weights': {}, 'features': list(data.columns), 'message': 'Insufficient data'}
  264. try:
  265. # 标准化
  266. normalized_data = self.mset.CRITIC_prepare(clean_data)
  267. # 计算权重
  268. weights = self.mset.CRITIC(normalized_data)
  269. # MSET评估
  270. health_score = self._run_mset_assessment(normalized_data.values, weights.values)
  271. return {
  272. 'health_score': float(health_score),
  273. 'weights': weights.to_dict(),
  274. 'features': list(data.columns)
  275. }
  276. except Exception as e:
  277. return {'health_score': -1, 'weights': {}, 'features': list(data.columns), 'message': str(e)}
  278. @lru_cache(maxsize=10)
  279. def _get_mset_model(self, train_data: tuple):
  280. """缓存MSET模型"""
  281. # 注意:由于lru_cache需要可哈希参数,这里使用元组
  282. arr = np.array(train_data)
  283. model = self._create_mset_core()
  284. model.genDLMatrix(arr)
  285. return model
  286. def _run_mset_assessment(self, data: np.ndarray, weights: np.ndarray) -> float:
  287. """执行MSET评估"""
  288. # 分割训练集和测试集
  289. split_idx = len(data) // 2
  290. train_data = data[:split_idx]
  291. test_data = data[split_idx:]
  292. # 使用缓存模型
  293. model = self._get_mset_model(tuple(map(tuple, train_data))) # 转换为可哈希的元组
  294. # 计算SPRT标志
  295. flags = model.calcSPRT(test_data, weights)
  296. return np.mean(flags)
  297. def _get_subsystem_weights(self, subsystems: List[str]) -> np.ndarray:
  298. """生成等权重的子系统权重向量"""
  299. n = len(subsystems)
  300. if n == 0:
  301. return np.array([])
  302. # 直接返回等权重向量
  303. return np.ones(n) / n
  304. # def _get_subsystem_weights(self, subsystems: List[str]) -> np.ndarray:
  305. # """动态生成子系统权重矩阵"""
  306. # n = len(subsystems)
  307. # if n == 0:
  308. # return np.array([])
  309. # # 定义子系统优先级
  310. # priority_order = ['generator', 'drive_train', 'nacelle', 'grid']
  311. # priority = {sys: idx for idx, sys in enumerate(priority_order) if sys in subsystems}
  312. # # 构建比较矩阵
  313. # matrix = np.ones((n, n))
  314. # for i in range(n):
  315. # for j in range(n):
  316. # if subsystems[i] in priority and subsystems[j] in priority:
  317. # if priority[subsystems[i]] < priority[subsystems[j]]:
  318. # matrix[i,j] = 3
  319. # elif priority[subsystems[i]] > priority[subsystems[j]]:
  320. # matrix[i,j] = 1/3
  321. # # AHP计算权重
  322. # weights, _ = self.mset.ahp(matrix)
  323. # return weights