Temp_Diag.PY 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. # @Time : 2019-6-19
  2. # @Author : wilbur.cheng@SKF
  3. # @FileName: baseMSET.py
  4. # @Software: a package in skf anomaly detection library to realize multivariate state estimation technique
  5. # this package has included all the functions used in MSET, similarity calculation, state memory matrix D,
  6. # normal state matrix L, residual calculation, and the basic SPRT (Sequential Probability Ratio Test)
  7. # function for binary hypothesis testing.
  8. #
  9. import numpy as np
  10. import pandas as pd
  11. import matplotlib.pyplot as plt
  12. from sklearn.neighbors import BallTree
  13. import openpyxl
  14. import time
  15. #from scikit-learn.neighbors import BallTree
  16. class MSET():
  17. matrixD = None
  18. matrixL = None
  19. healthyResidual = None
  20. normalDataBallTree = None
  21. def __init__(self):
  22. self.model = None
  23. def calcSimilarity(self, x, y, m = 'euc'):
  24. """
  25. Calcualte the similartity of two feature vector
  26. :param x: one of input feature list
  27. :param y: one of input feature list
  28. :param m: method of the similarity calculation method, default is the Eucilidean distance named 'euc';
  29. a city block distance function is used when m set to "cbd'.
  30. :return: the two feature similarity, float, range (0,1)
  31. """
  32. if (len(x) != len(y)):
  33. return 0
  34. if (m == 'cbd'):
  35. dSimilarity = [1/(1+np.abs(p-q)) for p,q in zip(x,y)]
  36. dSimilarity = np.sum(dSimilarity)/len(x)
  37. else:
  38. dSimilarity = [np.power(p-q,2) for p, q in zip(x, y)]
  39. dSimilarity = 1/(1+np.sqrt(np.sum(dSimilarity)))
  40. return dSimilarity
  41. def genDLMatrix(self, trainDataset, dataSize4D=100, dataSize4L=50):
  42. """
  43. automatically generate the D and L matrix from training data set, assuming the training data set is all normal
  44. state data.
  45. :param trainDataset: 2D array, [count of data, length of feature]
  46. :param dataSize4D: minimized count of state for matrix D
  47. :param dataSize4L: minimized count of state for matrix L
  48. :return: 0 if successful, -1 if fail
  49. """
  50. [m,n] = np.shape(trainDataset)
  51. if m < dataSize4D + dataSize4L:
  52. print('training dataset is too small to generate the matrix D and L')
  53. return -1
  54. self.matrixD = []
  55. selectIndex4D = []
  56. # Step 1: add all the state with minimum or maximum value in each feature into Matrix D
  57. for i in range(0, n):
  58. feature_i = trainDataset[:,i]
  59. minIndex = np.argmin(feature_i)
  60. maxIndex = np.argmax(feature_i)
  61. self.matrixD.append(trainDataset[minIndex, :].tolist())
  62. selectIndex4D.append(minIndex)
  63. self.matrixD.append(trainDataset[maxIndex, :].tolist())
  64. selectIndex4D.append(maxIndex)
  65. # Step 2: iteratively add the state with the maximum average distance to the states in selected matrixD
  66. while(1):
  67. if (len(selectIndex4D) >= dataSize4D):
  68. break
  69. # Get the free state list
  70. freeStateList = list(set(np.arange(0, len(trainDataset))) - set(selectIndex4D))
  71. # Calculate the average dist of each state in free to selected state in matrix D
  72. distList = []
  73. for i in freeStateList:
  74. tmpState = trainDataset[i]
  75. tmpDist = [1-self.calcSimilarity(x, tmpState) for x in self.matrixD]
  76. distList.append(np.mean(tmpDist))
  77. # select the free state with largest average distance to states in matrixD, and update matrixD
  78. selectId = freeStateList[distList.index(np.max(distList))]
  79. self.matrixD.append(trainDataset[selectId, :].tolist())
  80. selectIndex4D.append(selectId)
  81. #format matrixD from list to array
  82. self.matrixD = np.array(self.matrixD)
  83. self.normalDataBallTree = BallTree(self.matrixD, leaf_size=4, metric = lambda i,j: 1-self.calcSimilarity(i,j))
  84. # Step 3. select remaining state for matrix L
  85. #index4L = list(set(np.arange(0, len(trainDataset))) - set(selectIndex4D))
  86. #self.matrixL = trainDataset[index4L, :]
  87. # consider the limited dataset, using all the train data to matrix L
  88. self.matrixL = trainDataset
  89. # Calculate the healthy Residual from matrix L
  90. lamdaRatio = 1e-3
  91. [m, n] = np.shape(self.matrixD)
  92. self.DDSimilarity = np.array([[1-self.calcSimilarity(x,y) for x in self.matrixD] for y in self.matrixD] + lamdaRatio*np.eye(n))
  93. self.DDSimilarity = 1/self.DDSimilarity
  94. #self.healthyResidual = self.calcResidual(self.matrixL)
  95. self.healthyResidual = self.calcResidualByLocallyWeightedLR(self.matrixL)
  96. return 0
  97. def calcResidualByLocallyWeightedLR(self, newStates):
  98. """
  99. find the K-nearest neighbors for each input state, then calculate the estimated state by locally weighted average.
  100. :param newStates: input states list
  101. :return: residual R_x
  102. """
  103. [m,n] = np.shape(newStates)
  104. est_X = []
  105. # print(newStates)
  106. for x in newStates:
  107. (dist, iList) = self.normalDataBallTree.query([x], 20, return_distance=True)
  108. weight = 1/(dist[0]+1e-1)
  109. weight = weight/sum(weight)
  110. eState = np.sum([w*self.matrixD[i] for w,i in zip(weight, iList[0])])
  111. est_X.append(eState)
  112. est_X = np.reshape(est_X, (len(est_X),1))
  113. # print(est_X)
  114. # print(newStates)
  115. return est_X - newStates
  116. def calcStateResidual(self, newsStates):
  117. stateResidual = self.calcResidualByLocallyWeightedLR(newsStates)
  118. return stateResidual
  119. def calcSPRT(self, newsStates, feature_weight, alpha=0.1, beta=0.1, decisionGroup=5):
  120. """
  121. anomaly detection based Wald's SPRT algorithm, refer to A.Wald, Sequential Analysis,Wiley, New York, NY, USA, 1947
  122. :param newsStates: input states list
  123. :param feature_weight: the important weight for each feature, Normalized and Nonnegative
  124. :param alpha: prescribed false alarm rate, 0 < alpha < 1
  125. :param beta: prescribed miss alarm rate, 0 < beta < 1
  126. :param decisionGroup: length of the test sample when the decision is done
  127. :return: anomaly flag for each group of states, 1:anomaly, -1:normal, (-1:1): unable to decision
  128. """
  129. # Step 1. transfer the raw residual vector to dimension reduced residual using feature weight
  130. #stateResidual = self.calcResidual(newsStates)
  131. stateResidual = self.calcResidualByLocallyWeightedLR(newsStates)
  132. # print(stateResidual)
  133. weightedStateResidual = [np.dot(x, feature_weight) for x in stateResidual]
  134. # print(weightedStateResidual)
  135. weightedHealthyResidual = [np.dot(x, feature_weight) for x in self.healthyResidual]
  136. '''
  137. plt.subplot(211)
  138. plt.plot(weightedHealthyResidual)
  139. plt.xlabel('Sample index')
  140. plt.ylabel('Healthy State Residual')
  141. plt.subplot(212)
  142. plt.plot(weightedStateResidual)
  143. plt.xlabel('Sample index')
  144. plt.ylabel('All State Residual')
  145. plt.show()
  146. '''
  147. # Calculate the distribution of health state residual
  148. mu0 = np.mean(weightedHealthyResidual)
  149. sigma0 = np.std(weightedHealthyResidual)
  150. #sigma1 = np.std(weightedStateResidual)
  151. lowThres = np.log(beta/(1-alpha))
  152. highThres = np.log((1-beta)/alpha)
  153. flag = []
  154. for i in range(0, len(newsStates)-decisionGroup+1):
  155. # For each group to calculate the new state residual distribution
  156. # Then check the hypothesis testing results
  157. mu1 = np.mean(weightedStateResidual[i:i+decisionGroup])
  158. si = np.sum(weightedStateResidual[i:i+decisionGroup])*(mu1-mu0)/sigma0**2 - decisionGroup*(mu1**2-mu0**2)/(2*sigma0**2)
  159. if (si > highThres):
  160. si = highThres
  161. if (si < lowThres):
  162. si = lowThres
  163. if (si > 0):
  164. si = si/highThres
  165. if (si < 0):
  166. si = si/lowThres
  167. flag.append(si)
  168. return flag
  169. if __name__=='__main__':
  170. start_time = time.time()
  171. myMSET = MSET()
  172. # 1、计算各子系统的健康度(子系统包括:发电机组、传动系统(直驱机组无齿轮箱、无数据)、机舱系统、变流器系统、电网环境、辅助系统(无数据))
  173. # 1.1、发电机组健康度评分
  174. Title = pd.read_excel(r'34_QITAIHE.xlsx', header=None, nrows=1, usecols=[12, 13, 14])
  175. df_D = pd.read_excel(r'34_QITAIHE.xlsx',
  176. usecols=[0,12, 13, 14,], parse_dates=True) # 读取温度指标:齿轮箱油温12、驱动侧发电机轴承温度13、非驱动侧发电机轴承温度14
  177. cols = df_D.columns
  178. df_D[cols] = df_D[cols].apply(pd.to_numeric, errors='coerce')
  179. df_D = df_D.dropna() # 删除空行和非数字项
  180. x_date = df_D.iloc[len(df_D) // 2 + 1:, 0] #获取时间序列
  181. x_date = pd.to_datetime(x_date)
  182. df_Temp = df_D.iloc[:, 1:] #获取除时间列以外的数据
  183. df_Temp_values = df_Temp.values
  184. df_Temp_values = np.array(df_Temp_values)
  185. [m, n] = np.shape(df_Temp_values)
  186. # Residual = []
  187. flag_Spart_data = []
  188. for i in range(0, n):
  189. df_Temp_i = df_Temp_values[:, i]
  190. trainDataSet_data = df_Temp_i[0:len(df_Temp_i) // 2]
  191. testDataSet_data = df_Temp_i[len(df_Temp_i) // 2 + 1:]
  192. trainDataSet_data = np.reshape(trainDataSet_data, (len(trainDataSet_data), 1))
  193. testDataSet_data = np.reshape(testDataSet_data, (len(testDataSet_data), 1))
  194. myMSET.genDLMatrix(trainDataSet_data, 60, 5)
  195. # stateResidual = self.calcStateResidual(testDataSet_data)
  196. flag_data = myMSET.calcSPRT(testDataSet_data, np.array(1), decisionGroup=1)
  197. # Residual.append(stateResidual)
  198. flag_Spart_data.append(flag_data)
  199. flag_Spart_data = np.array(flag_Spart_data)
  200. flag_Spart_data = flag_Spart_data.T
  201. Temp1 = flag_Spart_data[:,0]
  202. Temp2 = flag_Spart_data[:,1]
  203. Temp3 = flag_Spart_data[:,2]
  204. Temp1_lable = Title.iloc[0, 0]
  205. Temp2_lable = Title.iloc[0, 1]
  206. Temp3_lable = Title.iloc[0, 2]
  207. print(x_date)
  208. # alarmedFlag = np.array([[i, Temp1[i]] for i, x in enumerate(Temp1) if x > 0.99]) # Flag中选出大于0.99的点
  209. plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签
  210. plt.close('all')
  211. plt.subplot(311)
  212. plt.plot(x_date, Temp1, 'b-o', label=Temp1_lable)
  213. plt.ylabel(Temp1_lable)
  214. plt.xlabel('时间')
  215. # plt.scatter(alarmedFlag1[:, 0], alarmedFlag1[:, 2], marker='x', c='r')
  216. plt.subplot(312)
  217. plt.plot(x_date, Temp2)
  218. plt.ylabel(Temp2_lable)
  219. plt.xlabel('时间')
  220. #plt.scatter(alarmedFlag[:, 0], alarmedFlag[:, 1], marker='x', c='r')
  221. plt.subplot(313)
  222. plt.plot(x_date, Temp3)
  223. plt.ylabel(Temp3_lable)
  224. plt.xlabel('时间')
  225. #plt.scatter(alarmedFlag[:, 0], alarmedFlag[:, 1], marker='x', c='r')
  226. plt.show()
  227. print(Title)
  228. print(flag_Spart_data)
  229. print(np.shape(flag_Spart_data))
  230. end_time = time.time()
  231. execution_time = end_time - start_time
  232. print(f"Execution time: {execution_time} seconds")
  233. #
  234. '''
  235. f = open("speed_vib.txt", "r")
  236. data1 = f.read()
  237. f.close()
  238. data1 = data1.split('\n')
  239. rpm = [(row.split('\t')[0]).strip() for row in data1]
  240. vib = [(row.split('\t')[-1]).strip() for row in data1]
  241. # print(rpm)
  242. rpm = np.array(rpm).astype(np.float64)
  243. vib = np.array(vib).astype(np.float64)
  244. #vib = [(x-np.mean(vib))/np.std(vib) for x in vib]
  245. #print(vib)
  246. trainDataSet = [vib[i] for i in range(0,100) if vib[i] < 5]
  247. trainDataSet = np.reshape(trainDataSet,(len(trainDataSet),1))
  248. testDataSet = np.reshape(vib, (len(vib),1))
  249. '''
  250. # Title = pd.read_csv(r'F1710001001.csv', header=None, nrows=1, usecols=[36,37,38], encoding='gbk')
  251. '''
  252. alarmedFlag = np.array([[i, flag[i]] for i, x in enumerate(flag) if x > 0.99]) # Flag中选出大于0.99的点
  253. plt.close('all')
  254. plt.subplot(211)
  255. plt.plot(testDataSet)
  256. plt.ylabel('Vibration')
  257. plt.xlabel('Sample index')
  258. plt.subplot(212)
  259. plt.plot(flag)
  260. plt.ylabel('SPRT results')
  261. plt.xlabel('Sample index')
  262. plt.scatter(alarmedFlag[:,0], alarmedFlag[:,1], marker='x',c='r')
  263. plt.show()
  264. '''