Temp_Diag.PY 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # temp_diag.py
  2. import numpy as np
  3. import pandas as pd
  4. from sklearn.neighbors import BallTree
  5. from sqlalchemy import create_engine, text
  6. import math
  7. class MSET_Temp:
  8. """
  9. 基于 MSET + SPRT 的温度趋势/阈值分析类。
  10. 查询条件由 wind_turbine_number 列和 time_stamp 范围决定,
  11. SPRT 阈值固定为 0.99,calcSPRT 输出在 [-1,1]。
  12. """
  13. def __init__(self, windCode: str, windTurbineNumberList: list[str], startTime: str, endTime: str):
  14. """
  15. :param windCode: 风机类型或机组代码,用于拼表名。例如 "WOG01312" → 表名 "WOG01312_minute"
  16. :param windTurbineNumberList: 要查询的 wind_turbine_number(风机编号)列表
  17. :param startTime: 起始时间(字符串),格式 "YYYY-MM-DD HH:MM"
  18. :param endTime: 结束时间(字符串),格式 "YYYY-MM-DD HH:MM"
  19. """
  20. self.windCode = windCode.strip()
  21. self.windTurbineNumberList = windTurbineNumberList
  22. # 强制保留到秒
  23. self.startTime = startTime
  24. self.endTime = endTime
  25. # D/L 矩阵相关
  26. self.matrixD = None
  27. self.matrixL = None
  28. self.healthyResidual = None
  29. self.normalDataBallTree = None
  30. # def _truncate_to_seconds(self, dt_str: str) -> str:
  31. # """
  32. # 将用户可能传进来的 ISO 时间字符串或包含毫秒的字符串
  33. # 截断到秒,返回 "YYYY-MM-DD HH:MM:SS" 格式。
  34. # 例如: "2025-06-01T12:34:56.789Z" → "2025-06-01 12:34:56"
  35. # """
  36. # # 先将 'T' 替换成空格,去掉尾部可能的 "Z"
  37. # s = dt_str.replace("T", " ").rstrip("Z")
  38. # # 如果含有小数秒,截断
  39. # if "." in s:
  40. # s = s.split(".")[0]
  41. # # 如果还有 "+xx:xx" 时区后缀,也截断
  42. # if "+" in s:
  43. # s = s.split("+")[0]
  44. # return s.strip()
  45. def _get_data_by_filter(self) -> pd.DataFrame:
  46. """
  47. 按 wind_turbine_number 列和 time_stamp 时间范围批量查询,
  48. 返回一个完整的 DataFrame(已按 time_stamp 升序排序)。
  49. """
  50. table_name = f"{self.windCode}_minute"
  51. engine = create_engine(
  52. "mysql+pymysql://root:admin123456@106.120.102.238:10336/energy_data_prod"
  53. )
  54. # 准备 wind_turbine_number 列表的 SQL 片段:('WT1','WT2',...)
  55. turbines = ",".join(f"'{wt.strip()}'" for wt in self.windTurbineNumberList)
  56. sql = text(f"""
  57. SELECT *
  58. FROM {table_name}
  59. WHERE wind_turbine_number IN ({turbines})
  60. AND time_stamp BETWEEN :start AND :end
  61. ORDER BY time_stamp ASC
  62. """)
  63. df = pd.read_sql(sql, engine, params={"start": self.startTime, "end": self.endTime})
  64. return df
  65. def calcSimilarity(self, x: np.ndarray, y: np.ndarray, m: str = 'euc') -> float:
  66. """
  67. 计算向量 x 与 y 的相似度,(0,1] 区间:
  68. - m='euc' → 欧氏距离
  69. - m='cbd' → 城市街区距离
  70. """
  71. if len(x) != len(y):
  72. return 0.0
  73. if m == 'cbd':
  74. arr = [1.0 / (1.0 + abs(p - q)) for p, q in zip(x, y)]
  75. return float(np.sum(arr) / len(arr))
  76. else:
  77. diffsq = [(p - q) ** 2 for p, q in zip(x, y)]
  78. return float(1.0 / (1.0 + math.sqrt(np.sum(diffsq))))
  79. def genDLMatrix(self, trainDataset: np.ndarray, dataSize4D=100, dataSize4L=50) -> int:
  80. """
  81. 根据训练集 trainDataset 生成 D/L 矩阵:
  82. - 若样本数 < dataSize4D + dataSize4L,返回 -1
  83. - 否则构造 matrixD、matrixL,并用局部加权回归获得 healthyResidual,返回 0
  84. """
  85. m, n = trainDataset.shape
  86. if m < dataSize4D + dataSize4L:
  87. return -1
  88. # Step1:每个特征的最小/最大样本加入 matrixD
  89. self.matrixD = []
  90. selectIndex4D = []
  91. for i in range(n):
  92. col_i = trainDataset[:, i]
  93. idx_min = np.argmin(col_i)
  94. idx_max = np.argmax(col_i)
  95. self.matrixD.append(trainDataset[idx_min, :].tolist())
  96. selectIndex4D.append(idx_min)
  97. self.matrixD.append(trainDataset[idx_max, :].tolist())
  98. selectIndex4D.append(idx_max)
  99. # Step2:对剩余样本逐步选出“与 matrixD 平均距离最大”的样本,直至 matrixD 行数 = dataSize4D
  100. while len(selectIndex4D) < dataSize4D:
  101. freeList = list(set(range(len(trainDataset))) - set(selectIndex4D))
  102. distAvg = []
  103. for idx in freeList:
  104. tmp = trainDataset[idx, :]
  105. dlist = [1.0 - self.calcSimilarity(x, tmp) for x in self.matrixD]
  106. distAvg.append(np.mean(dlist))
  107. select_id = freeList[int(np.argmax(distAvg))]
  108. self.matrixD.append(trainDataset[select_id, :].tolist())
  109. selectIndex4D.append(select_id)
  110. self.matrixD = np.array(self.matrixD)
  111. # 用 matrixD 建 BallTree,用于局部加权回归
  112. self.normalDataBallTree = BallTree(
  113. self.matrixD,
  114. leaf_size=4,
  115. metric=lambda a, b: 1.0 - self.calcSimilarity(a, b)
  116. )
  117. # Step3:把所有训练样本都作为 matrixL
  118. self.matrixL = trainDataset.copy()
  119. # Step4:用局部加权回归算出健康残差
  120. self.healthyResidual = self.calcResidualByLocallyWeightedLR(self.matrixL)
  121. return 0
  122. def calcResidualByLocallyWeightedLR(self, newStates: np.ndarray) -> np.ndarray:
  123. """
  124. 对 newStates 中每个样本,使用 matrixD 的前 20 个最近邻做局部加权回归,计算残差。
  125. 返回形状 [len(newStates), 特征数] 的残差矩阵。
  126. """
  127. est_list = []
  128. for x in newStates:
  129. dist, idxs = self.normalDataBallTree.query([x], k=20, return_distance=True)
  130. w = 1.0 / (dist[0] + 1e-1)
  131. w = w / np.sum(w)
  132. est = np.sum([w_i * self.matrixD[j] for w_i, j in zip(w, idxs[0])], axis=0)
  133. est_list.append(est)
  134. est_arr = np.reshape(np.array(est_list), (len(est_list), -1))
  135. return est_arr - newStates
  136. def calcSPRT(
  137. self,
  138. newsStates: np.ndarray,
  139. feature_weight: np.ndarray,
  140. alpha: float = 0.1,
  141. beta: float = 0.1,
  142. decisionGroup: int = 5
  143. ) -> list[float]:
  144. """
  145. 对 newsStates 运行 Wald-SPRT,返回得分列表,长度 = len(newsStates) - decisionGroup + 1,
  146. 分数在 [-1, 1]:
  147. - 越接近 1 → 越“异常(危险)”
  148. - 越接近 -1 → 越“正常”
  149. """
  150. # 1) 计算残差并做特征加权
  151. stateRes = self.calcResidualByLocallyWeightedLR(newsStates)
  152. weightedStateResidual = [np.dot(x, feature_weight) for x in stateRes]
  153. weightedHealthyResidual = [np.dot(x, feature_weight) for x in self.healthyResidual]
  154. # 2) 健康残差的分布统计
  155. mu0 = float(np.mean(weightedHealthyResidual))
  156. sigma0 = float(np.std(weightedHealthyResidual))
  157. # 3) 计算 SPRT 的上下阈值
  158. lowThres = np.log(beta / (1.0 - alpha)) # < 0
  159. highThres = np.log((1.0 - beta) / alpha) # > 0
  160. flags: list[float] = []
  161. length = len(weightedStateResidual)
  162. for i in range(0, length - decisionGroup + 1):
  163. segment = weightedStateResidual[i : i + decisionGroup]
  164. mu1 = float(np.mean(segment))
  165. si = (
  166. np.sum(segment) * (mu1 - mu0) / (sigma0**2)
  167. - decisionGroup * ((mu1**2) - (mu0**2)) / (2.0 * (sigma0**2))
  168. )
  169. # 限制 si 在 [lowThres, highThres] 之内
  170. si = max(min(si, highThres), lowThres)
  171. # 正负归一化
  172. if si > 0:
  173. norm_si = float(si / highThres)
  174. else:
  175. norm_si = float(si / lowThres)
  176. flags.append(norm_si)
  177. return flags
  178. def check_threshold(self) -> pd.DataFrame:
  179. """
  180. 阈值分析(阈值固定 0.99)。返回长格式 DataFrame,列:
  181. ["time_stamp", "temp_channel", "SPRT_score", "status"]
  182. status = "危险" if SPRT_score > 0.99 else "正常"。
  183. """
  184. THRESHOLD = 0.99
  185. # 1) 按风机编号 + 时间范围查询原始数据
  186. df_concat = self._get_data_by_filter()
  187. if df_concat.empty:
  188. return pd.DataFrame(columns=["time_stamp", "temp_channel", "SPRT_score", "status"])
  189. # 2) 筛选存在的温度列
  190. temp_cols_all = [
  191. 'main_bearing_temperature',
  192. 'gearbox_oil_temperature',
  193. 'generatordrive_end_bearing_temperature',
  194. 'generatornon_drive_end_bearing_temperature'
  195. ]
  196. temp_cols = [c for c in temp_cols_all if c in df_concat.columns]
  197. if not temp_cols:
  198. return pd.DataFrame(columns=["time_stamp", "temp_channel", "SPRT_score", "status"])
  199. # 3) 转数值 & 删除 NaN
  200. df_concat[temp_cols] = df_concat[temp_cols].apply(pd.to_numeric, errors='coerce')
  201. df_concat = df_concat.dropna(subset=temp_cols + ['time_stamp'])
  202. if df_concat.empty:
  203. return pd.DataFrame(columns=["time_stamp", "temp_channel", "SPRT_score", "status"])
  204. # 4) time_stamp 转 datetime
  205. df_concat['time_stamp'] = pd.to_datetime(df_concat['time_stamp'])
  206. x_date = df_concat['time_stamp']
  207. # 5) 抽取温度列到 NumPy 数组
  208. arr = df_concat[temp_cols].values # shape = [总记录数, 通道数]
  209. m, n = arr.shape
  210. half = m // 2
  211. all_flags: list[list[float]] = []
  212. for i in range(n):
  213. channel = arr[:, i]
  214. train = channel[:half].reshape(-1, 1)
  215. test = channel[half:].reshape(-1, 1)
  216. # 用训练集构造 D/L 矩阵
  217. if self.genDLMatrix(train, dataSize4D=60, dataSize4L=5) != 0:
  218. # 如果训练集样本不足,直接返回空表
  219. return pd.DataFrame(columns=["time_stamp", "temp_channel", "SPRT_score", "status"])
  220. feature_w = np.array([1.0])
  221. flags = self.calcSPRT(test, feature_w, decisionGroup=1)
  222. all_flags.append(flags)
  223. # 6) 合并为宽表,再 melt 成长表
  224. flags_arr = np.array(all_flags) # shape = [通道数, 测试样本数]
  225. num_test = flags_arr.shape[1]
  226. ts = x_date.iloc[half : half + num_test].reset_index(drop=True)
  227. wide = pd.DataFrame({"time_stamp": ts})
  228. for idx, col in enumerate(temp_cols):
  229. wide[col] = flags_arr[idx, :]
  230. df_long = wide.melt(
  231. id_vars=["time_stamp"],
  232. value_vars=temp_cols,
  233. var_name="temp_channel",
  234. value_name="SPRT_score"
  235. )
  236. # 把 time_stamp 从 datetime 转成字符串,格式 "YYYY-MM-DD HH:MM:SS"
  237. df_long['time_stamp'] = pd.to_datetime(df_long['time_stamp']).dt.strftime("%Y-%m-%d %H:%M:%S")
  238. # 7) 添加状态列:SPRT_score > 0.99 → “危险”,否则 “正常”
  239. df_long['status'] = df_long['SPRT_score'].apply(
  240. lambda x: "危险" if x > THRESHOLD else "正常"
  241. )
  242. # 8) 将 temp_channel 列的英文名称改为中文
  243. temp_channel_mapping = {
  244. 'main_bearing_temperature': '主轴承温度',
  245. 'gearbox_oil_temperature': '齿轮箱油温',
  246. 'generatordrive_end_bearing_temperature': '发电机驱动端轴承温度',
  247. 'generatornon_drive_end_bearing_temperature': '发电机非驱动端轴承温度'
  248. }
  249. df_long['temp_channel'] = df_long['temp_channel'].map(temp_channel_mapping)
  250. return df_long
  251. def get_trend(self) -> dict:
  252. """
  253. 趋势分析
  254. 获取温度趋势:将温度数据按时间返回。
  255. 返回格式:{
  256. "timestamps": [ISO8601 字符串列表],
  257. "channels": [
  258. {"temp_channel": "main_bearing_temperature", "values": [浮点列表]},
  259. {"temp_channel": "gearbox_oil_temperature", "values": [...]},
  260. ...
  261. ],
  262. "unit": "°C"
  263. }
  264. """
  265. df = self._get_data_by_filter()
  266. if df.empty:
  267. return {"timestamps": [], "channels": [], "unit": "°C"}
  268. # 定义所有需要检查的温度列
  269. temp_cols_all = [
  270. 'main_bearing_temperature',
  271. 'gearbox_oil_temperature',
  272. 'generatordrive_end_bearing_temperature',
  273. 'generatornon_drive_end_bearing_temperature'
  274. ]
  275. # 选择实际存在的列
  276. temp_cols = [c for c in temp_cols_all if c in df.columns]
  277. # 如果没有温度数据列,返回空数据
  278. if not temp_cols:
  279. return {"timestamps": [], "channels": [], "unit": "°C"}
  280. # 转数值,并删除 NaN
  281. df[temp_cols] = df[temp_cols].apply(pd.to_numeric, errors='coerce')
  282. df = df.dropna(subset=temp_cols + ['time_stamp'])
  283. # 转时间戳为 `YYYY-MM-DD HH:MM:SS` 格式
  284. df['time_stamp'] = pd.to_datetime(df['time_stamp']).dt.strftime("%Y-%m-%d %H:%M:%S")
  285. df = df.sort_values('time_stamp').reset_index(drop=True)
  286. # 时间戳格式化为 ISO 8601 字符串
  287. timestamps = df['time_stamp'].tolist()
  288. # 对每个通道,收集它在相应行的数值
  289. channels_data = []
  290. for col in temp_cols:
  291. channels_data.append({
  292. "temp_channel": col,
  293. "values": df[col].tolist()
  294. })
  295. # 将 temp_channel 列的英文名称改为中文
  296. temp_channel_mapping = {
  297. 'main_bearing_temperature': '主轴承温度',
  298. 'gearbox_oil_temperature': '齿轮箱油温',
  299. 'generatordrive_end_bearing_temperature': '发电机驱动端轴承温度',
  300. 'generatornon_drive_end_bearing_temperature': '发电机非驱动端轴承温度'
  301. }
  302. for channel in channels_data:
  303. channel['temp_channel'] = temp_channel_mapping.get(channel['temp_channel'], channel['temp_channel'])
  304. return {
  305. "timestamps": timestamps,
  306. "channels": channels_data,
  307. "unit": "°C"
  308. }