HealthAssessor.py 15 KB

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