No Description

v1_multifailure.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. # Csar Fdez, UdL, 2025
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import datetime
  5. import numpy as np
  6. import keras
  7. import os.path
  8. import pickle
  9. from keras import layers
  10. from optparse import OptionParser
  11. parser = OptionParser()
  12. parser.add_option("-t", "--train", dest="train", help="Trains the models (false)", default=False, action="store_true")
  13. (options, args) = parser.parse_args()
  14. # data files arrays. Index:
  15. # 0. No failure
  16. # 1. Blocked evaporator
  17. # 2. Full Blocked condenser
  18. # 3. Partial Blocked condenser
  19. # 4 Fan condenser not working
  20. # 5. Open door
  21. NumberOfFailures=5
  22. NumberOfFailures=4 # So far, we have only data for the first 4 types of failures
  23. datafiles=[]
  24. for i in range(NumberOfFailures+1):
  25. datafiles.append([])
  26. # Next set of ddata corresponds to Freezer, SP=-26
  27. datafiles[0]=['2024-08-07_5_','2024-08-08_5_']
  28. datafiles[1]=['2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_']
  29. datafiles[2]=['2024-12-18_5_','2024-12-19_5_']
  30. datafiles[3]=['2024-12-21_5_','2024-12-22_5_','2024-12-23_5_','2024-12-24_5_','2024-12-25_5_','2024-12-26_5_']
  31. datafiles[4]=['2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_']
  32. #datafiles[4]=[]
  33. # Features suggested by Xavier
  34. # Care with 'tc s3' because on datafiles[0] is always nulll
  35. # Seems to be incoropored in new tests
  36. features=['r1 s1','r1 s4','r1 s5','pa1 apiii']
  37. features=['r1 s1','r1 s2','r1 s3','r1 s4','r1 s5','r1 s6','r1 s7','r1 s8','r1 s9','r1 s10','r2 s1','r2 s2','r2 s3','r2 s4','r2 s5','r2 s6','r2 s7','r2 s8','r2 s9','pa1 apiii','tc s1','tc s2']
  38. NumFeatures=len(features)
  39. df_list=[]
  40. for i in range(NumberOfFailures+1):
  41. df_list.append([])
  42. for i in range(NumberOfFailures+1):
  43. dftemp=[]
  44. for f in datafiles[i]:
  45. print(" ", f)
  46. #df1 = pd.read_csv('./data/'+f+'.csv', parse_dates=['datetime'], dayfirst=True, index_col='datetime')
  47. df1 = pd.read_csv('./data/'+f+'.csv')
  48. dftemp.append(df1)
  49. df_list[i]=pd.concat(dftemp)
  50. # subsampled to 5' = 30 * 10"
  51. # We consider smaples every 5' because in production, we will only have data at this frequency
  52. subsamplingrate=30
  53. dataframe=[]
  54. for i in range(NumberOfFailures+1):
  55. dataframe.append([])
  56. for i in range(NumberOfFailures+1):
  57. datalength=df_list[i].shape[0]
  58. dataframe[i]=df_list[i].iloc[range(0,datalength,subsamplingrate)][features]
  59. dataframe[i].reset_index(inplace=True,drop=True)
  60. dataframe[i].dropna(inplace=True)
  61. # Train data is first 2/3 of data
  62. # Test data is: last 1/3 of data
  63. dataTrain=[]
  64. dataTest=[]
  65. for i in range(NumberOfFailures+1):
  66. dataTrain.append(dataframe[i].values[0:int(dataframe[i].shape[0]*2/3),:])
  67. dataTest.append(dataframe[i].values[int(dataframe[i].shape[0]*2/3):,:])
  68. def normalize2(train,test):
  69. # merges train and test
  70. means=[]
  71. stdevs=[]
  72. for i in range(NumFeatures):
  73. means.append(train[:,i].mean())
  74. stdevs.append(train[:,i].std())
  75. return( (train-means)/stdevs, (test-means)/stdevs )
  76. dataTrainNorm=[]
  77. dataTestNorm=[]
  78. for i in range(NumberOfFailures+1):
  79. dataTrainNorm.append([])
  80. dataTestNorm.append([])
  81. for i in range(NumberOfFailures+1):
  82. (dataTrainNorm[i],dataTestNorm[i])=normalize2(dataTrain[i],dataTest[i])
  83. def plotData():
  84. fig, axes = plt.subplots(
  85. nrows=NumberOfFailures+1, ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
  86. )
  87. for i in range(NumberOfFailures+1):
  88. axes[i][0].plot(np.concatenate((dataTrainNorm[i][:,0],dataTestNorm[i][:,0])),label="Fail "+str(i)+", feature 0")
  89. axes[i][1].plot(np.concatenate((dataTrainNorm[i][:,1],dataTestNorm[i][:,1])),label="Fail "+str(i)+", feature 1")
  90. #axes[1].legend()
  91. #axes[0].set_ylabel(features[0])
  92. #axes[1].set_ylabel(features[1])
  93. plt.show()
  94. #plotData()
  95. TIME_STEPS = 12
  96. def create_sequences(values, time_steps=TIME_STEPS):
  97. output = []
  98. for i in range(len(values) - time_steps + 1):
  99. output.append(values[i : (i + time_steps)])
  100. return np.stack(output)
  101. x_train=[]
  102. for i in range(NumberOfFailures+1):
  103. x_train.append(create_sequences(dataTrainNorm[i]))
  104. model=[]
  105. modelckpt_callback =[]
  106. es_callback =[]
  107. path_checkpoint=[]
  108. for i in range(NumberOfFailures+1):
  109. model.append([])
  110. model[i] = keras.Sequential(
  111. [
  112. layers.Input(shape=(x_train[i].shape[1], x_train[i].shape[2])),
  113. layers.Conv1D(
  114. filters=64,
  115. kernel_size=7,
  116. padding="same",
  117. strides=2,
  118. activation="relu",
  119. ),
  120. layers.Dropout(rate=0.2),
  121. layers.Conv1D(
  122. filters=32,
  123. kernel_size=7,
  124. padding="same",
  125. strides=2,
  126. activation="relu",
  127. ),
  128. layers.Conv1DTranspose(
  129. filters=32,
  130. kernel_size=7,
  131. padding="same",
  132. strides=2,
  133. activation="relu",
  134. ),
  135. layers.Dropout(rate=0.2),
  136. layers.Conv1DTranspose(
  137. filters=64,
  138. kernel_size=7,
  139. padding="same",
  140. strides=2,
  141. activation="relu",
  142. ),
  143. layers.Conv1DTranspose(filters=x_train[i].shape[2], kernel_size=7, padding="same"),
  144. ]
  145. )
  146. model[i].compile(optimizer=keras.optimizers.Adam(learning_rate=0.001), loss="mse")
  147. model[i].summary()
  148. path_checkpoint.append("model_v1_"+str(i)+"._checkpoint.weights.h5")
  149. es_callback.append(keras.callbacks.EarlyStopping(monitor="val_loss", min_delta=0, patience=15))
  150. modelckpt_callback.append(keras.callbacks.ModelCheckpoint( monitor="val_loss", filepath=path_checkpoint[i], verbose=1, save_weights_only=True, save_best_only=True,))
  151. if options.train:
  152. history=[]
  153. for i in range(NumberOfFailures+1):
  154. history.append(model[i].fit( x_train[i], x_train[i], epochs=400, batch_size=128, validation_split=0.3, callbacks=[ es_callback[i], modelckpt_callback[i] ],))
  155. fig, axes = plt.subplots(
  156. nrows=int(np.ceil((NumberOfFailures+1)/2)), ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
  157. )
  158. for i in range(int(np.ceil((NumberOfFailures+1)/2))):
  159. for j in range(2):
  160. r=2*i+j
  161. if r < NumberOfFailures+1:
  162. axes[i][j].plot(history[r].history["loss"], label="Training Loss")
  163. axes[i][j].plot(history[r].history["val_loss"], label="Val Loss")
  164. axes[i][j].legend()
  165. #plt.show()
  166. else:
  167. for i in range(NumberOfFailures+1):
  168. model[i].load_weights(path_checkpoint[i])
  169. x_train_pred=[]
  170. train_mae_loss=[]
  171. threshold=[]
  172. for i in range(NumberOfFailures+1):
  173. x_train_pred.append(model[i].predict(x_train[i]))
  174. train_mae_loss.append(np.mean(np.abs(x_train_pred[i] - x_train[i]), axis=1))
  175. threshold.append(np.max(train_mae_loss[i],axis=0))
  176. print("Threshold : ",threshold)
  177. for i in range(NumberOfFailures+1):
  178. threshold[i]=threshold[i]*1.3
  179. # Threshold is enlarged because, otherwise, for subsamples at 5' have many false positives
  180. # 1st scenario. Detect only anomaly. Later, we will classiffy it
  181. # Test data= testnormal + testfail1 + testtail2 + testfail3 + testfail4 + testnormal
  182. d=np.vstack((dataTestNorm[0],dataTestNorm[1],dataTestNorm[2],dataTestNorm[3],dataTestNorm[4],dataTestNorm[0]))
  183. x_test = create_sequences(d)
  184. x_test_pred = model[0].predict(x_test)
  185. test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
  186. # Define ranges for plotting in different colors
  187. testRanges=[]
  188. r=dataTestNorm[0].shape[0]
  189. testRanges.append([0,r])
  190. for i in range(1,NumberOfFailures+1):
  191. rnext=r+dataTestNorm[i].shape[0]
  192. testRanges.append([r,rnext] )
  193. r=rnext
  194. testRanges.append([r, x_test.shape[0] ])
  195. def AtLeastOneTrue(x):
  196. for i in range(NumFeatures):
  197. if x[i]:
  198. return True
  199. return False
  200. anomalies = test_mae_loss > threshold[0]
  201. anomalous_data_indices = []
  202. for i in range(anomalies.shape[0]):
  203. if AtLeastOneTrue(anomalies[i]):
  204. #if anomalies[i][0] or anomalies[i][1] or anomalies[i][2] or anomalies[i][3]:
  205. anomalous_data_indices.append(i)
  206. #print(anomalous_data_indices)
  207. # Let's plot only a couple of features
  208. def plotData2():
  209. fig, axes = plt.subplots(
  210. nrows=2, ncols=1, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
  211. )
  212. axes[0].plot(range(len(x_train[0])),x_train[0][:,0,0],label="normal")
  213. axes[0].plot(range(len(x_train[0]),len(x_train[0])+len(x_test)),x_test[:,0,0],label="abnormal")
  214. axes[0].plot(len(x_train[0])+np.array(anomalous_data_indices),x_test[anomalous_data_indices,0,0],color='red',marker='.',linewidth=0,label="abnormal detection")
  215. axes[0].legend()
  216. axes[1].plot(range(len(x_train[0])),x_train[0][:,0,1],label="normal")
  217. axes[1].plot(range(len(x_train[0]),len(x_train[0])+len(x_test)),x_test[:,0,1],label="abnormal")
  218. axes[1].plot(len(x_train[0])+np.array(anomalous_data_indices),x_test[anomalous_data_indices,0,1],color='red',marker='.',linewidth=0,label="abnormal detection")
  219. axes[1].legend()
  220. axes[0].set_ylabel(features[0])
  221. axes[1].set_ylabel(features[1])
  222. plt.show()
  223. #plotData2()
  224. # 2nd scenario. Go over anomalies and classify it by less error
  225. '''
  226. #This code works, but too slow
  227. anomalous_data_type=[]
  228. for i in anomalous_data_indices:
  229. error=[]
  230. for m in range(1,NumberOfFailures+1):
  231. error.append(np.mean(np.mean(np.abs(model[m].predict(x_test[i:i+1,:,:])-x_test[i:i+1,:,:]),axis=1)))
  232. anomalous_data_type.append(np.argmin(error)+1)
  233. '''
  234. anomalous_data_type=[]
  235. x_test_predict=[]
  236. for m in range(NumberOfFailures+1):
  237. x_test_predict.append(model[m].predict(x_test))
  238. for i in anomalous_data_indices:
  239. error=[]
  240. for m in range(1,NumberOfFailures+1):
  241. error.append(np.mean(np.mean(np.abs(x_test_predict[m][i:i+1,:,:]-x_test[i:i+1,:,:]),axis=1)))
  242. anomalous_data_type.append(np.argmin(error)+1)
  243. # For plotting purposes
  244. anomalous_data_indices_by_failure=[]
  245. for i in range(NumberOfFailures+1):
  246. anomalous_data_indices_by_failure.append([])
  247. for i in range(len(anomalous_data_indices)):
  248. print(i," ",anomalous_data_type[i])
  249. anomalous_data_indices_by_failure[anomalous_data_type[i]].append(anomalous_data_indices[i])
  250. colorline=['violet','lightcoral','cyan','lime','grey']
  251. colordot=['darkviolet','red','blue','green','black']
  252. featuresToPlot=['r1 s1','r1 s3','r1 s5','r2 s3','r2 s4','pa1 apiii','tc s1','tc s2','tc s3']
  253. featuresToPlot=features
  254. indexesToPlot=[]
  255. for i in featuresToPlot:
  256. indexesToPlot.append(features.index(i))
  257. def plotData3():
  258. NumFeaturesToPlot=len(indexesToPlot)
  259. fig, axes = plt.subplots(
  260. nrows=NumFeaturesToPlot, ncols=1, figsize=(25, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
  261. )
  262. for i in range(NumFeaturesToPlot):
  263. init=0
  264. end=len(x_train[0])
  265. axes[i].plot(range(init,end),x_train[0][:,0,indexesToPlot[i]],label="normal train")
  266. #axes.plot(range(len(x_train[0]),len(x_train[0])+len(x_test)),x_test[:,0,0],label="abnormal")
  267. init=end
  268. end+=testRanges[0][1]
  269. axes[i].plot(range(init,end),x_test[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]],label="normal test")
  270. init=end
  271. end+=(testRanges[1][1]-testRanges[1][0])
  272. for j in range(1,NumberOfFailures+1):
  273. axes[i].plot(range(init,end),x_test[testRanges[j][0]:testRanges[j][1],0,indexesToPlot[i]],label="fail type "+str(j), color=colorline[j-1])
  274. init=end
  275. end+=(testRanges[j+1][1]-testRanges[j+1][0])
  276. axes[i].plot(len(x_train[0])+np.array(anomalous_data_indices_by_failure[j]),x_test[anomalous_data_indices_by_failure[j],0,indexesToPlot[i]],color=colordot[j-1],marker='.',linewidth=0,label="abnormal detection type "+str(j))
  277. init=end-(testRanges[NumberOfFailures+1][1]-testRanges[NumberOfFailures+1][0])
  278. end=init+(testRanges[0][1]-testRanges[0][0])
  279. axes[i].plot(range(init,end),x_test[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]],color='orange')
  280. if i==0:
  281. axes[i].legend(bbox_to_anchor=(1, 0.5))
  282. axes[i].set_ylabel(features[indexesToPlot[i]])
  283. axes[i].grid()
  284. plt.show()
  285. def anomalyMetric(testList): # first of list is non failure data
  286. x_test = create_sequences(testList[0])
  287. x_test_pred = model[0].predict(x_test)
  288. test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
  289. anomalies = test_mae_loss > threshold[0]
  290. count=0
  291. for i in range(anomalies.shape[0]):
  292. if AtLeastOneTrue(anomalies[i]):
  293. count+=1
  294. FP=count/anomalies.shape[0]
  295. count=0
  296. for i in range(anomalies.shape[0]):
  297. if AtLeastOneTrue(anomalies[i]):
  298. count+=1
  299. FP=count/anomalies.shape[0]
  300. TN=np.zeros((NumberOfFailures))
  301. for i in range(1,len(testList)):
  302. x_test = create_sequences(testList[i])
  303. x_test_pred = model[0].predict(x_test)
  304. test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
  305. anomalies = test_mae_loss > threshold[0]
  306. count=0
  307. for j in range(anomalies.shape[0]):
  308. if AtLeastOneTrue(anomalies[j]):
  309. count+=1
  310. TN[i-1] = count/anomalies.shape[0]
  311. print("FP: ",FP)
  312. print("TN: ",TN)
  313. return (1-FP)*NumberOfFailures+TN.sum()
  314. anomalyMetric([dataTestNorm[0],dataTestNorm[1],dataTestNorm[2],dataTestNorm[3],dataTestNorm[4]])
  315. plotData3()

Powered by TurnKey Linux.