cesar 2 semanas atrás
pai
commit
be3a175eb2

BIN
paper/Adapt25_Paper_Template_updated_AKO_DRAFT_final.docx Ver arquivo


+ 279
- 0
v0_unsupervised.py Ver arquivo

@@ -0,0 +1,279 @@
1
+# Csar Fdez, UdL, 2025
2
+#  Unsupervised classification. Uses tslearn
3
+#  https://tslearn.readthedocs.io/en/stable/index.html
4
+
5
+
6
+import pandas as pd
7
+import matplotlib.pyplot as plt
8
+import datetime
9
+import numpy as np
10
+import keras
11
+import os.path
12
+from optparse import OptionParser
13
+import copy
14
+import pickle
15
+from tslearn.clustering import TimeSeriesKMeans
16
+from collections import Counter
17
+
18
+parser = OptionParser()
19
+parser.add_option("-t", "--train", dest="train", help="Trains the models (false)", default=False, action="store_true")
20
+parser.add_option("-n", "--timesteps", dest="timesteps", help="TIME STEPS ", default=12)
21
+
22
+(options, args) = parser.parse_args()
23
+
24
+
25
+# data files arrays. Index:
26
+# 0.  No failure
27
+# 1.  Blocked evaporator
28
+# 2.   Full Blocked condenser
29
+# 3.   Partial Blocked condenser
30
+# 4   Fan condenser not working
31
+# 5.  Open door
32
+
33
+
34
+NumberOfFailures=4  # So far, we have only data for the first 4 types of failures
35
+datafiles=[]
36
+for i in range(NumberOfFailures+1):
37
+    datafiles.append([])
38
+
39
+# Next set of ddata corresponds to Freezer, SP=-26
40
+datafiles[0]=['2024-08-07_5_','2024-08-08_5_','2025-01-25_5_','2025-01-26_5_','2025-01-27_5_','2025-01-28_5_'] 
41
+datafiles[1]=['2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_'] 
42
+#datafiles[1]=['2024-12-17_5_','2024-12-16_5_','2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_'] #   This have transitions
43
+datafiles[2]=['2024-12-18_5_','2024-12-19_5_'] 
44
+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_'] 
45
+datafiles[4]=['2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_'] 
46
+#datafiles[4]=['2024-12-27_5_','2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_']  #   This have transitions
47
+
48
+#datafiles[4]=[] 
49
+
50
+# Features suggested by Xavier
51
+# Care with 'tc s3' because on datafiles[0] is always nulll
52
+# Seems to be incoropored in new tests
53
+
54
+#r1s5 supply air flow temperature
55
+#r1s1 inlet evaporator temperature
56
+#r1s4 condenser outlet
57
+
58
+# VAriables r1s4 and pa1 apiii  may not exists in cloud controlers
59
+
60
+
61
+features=['r1 s1','r1 s4','r1 s5','pa1 apiii']
62
+features=['r1 s1','r1 s4','r1 s5']
63
+featureNames={}
64
+featureNames['r1 s1']='$T_{evap}$'
65
+featureNames['r1 s4']='$T_{cond}$'
66
+featureNames['r1 s5']='$T_{air}$'
67
+featureNames['pa1 apiii']='$P_{elec}$'
68
+
69
+unitNames={}
70
+unitNames['r1 s1']='$(^{o}C)$'
71
+unitNames['r1 s4']='$(^{o}C)$'
72
+unitNames['r1 s5']='$(^{o}C)$'
73
+unitNames['pa1 apiii']='$(W)$'
74
+
75
+
76
+#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']
77
+
78
+#features=['r2 s2', 'tc s1','r1 s10','r1 s6','r2 s8']
79
+
80
+NumFeatures=len(features)
81
+
82
+df_list=[]
83
+for i in range(NumberOfFailures+1):
84
+    df_list.append([])
85
+
86
+for i in range(NumberOfFailures+1):
87
+    dftemp=[]
88
+    for f in datafiles[i]:
89
+        print("                 ", f)
90
+        #df1 = pd.read_csv('./data/'+f+'.csv', parse_dates=['datetime'], dayfirst=True, index_col='datetime')
91
+        df1 = pd.read_csv('./data/'+f+'.csv')
92
+        dftemp.append(df1)
93
+    df_list[i]=pd.concat(dftemp)
94
+
95
+
96
+# subsampled to 5'  =  30 * 10"
97
+# We consider smaples every 5' because in production, we will only have data at this frequency
98
+subsamplingrate=30
99
+
100
+dataframe=[]
101
+for i in range(NumberOfFailures+1):
102
+    dataframe.append([])
103
+
104
+for i in range(NumberOfFailures+1):
105
+    datalength=df_list[i].shape[0]
106
+    dataframe[i]=df_list[i].iloc[range(0,datalength,subsamplingrate)][features]
107
+    dataframe[i].reset_index(inplace=True,drop=True)
108
+    dataframe[i].dropna(inplace=True)
109
+
110
+
111
+# Train data is first 2/3 of data
112
+# Test data is: last 1/3 of data 
113
+dataTrain=[]
114
+dataTest=[]
115
+for i in range(NumberOfFailures+1):
116
+    dataTrain.append(dataframe[i].values[0:int(dataframe[i].shape[0]*2/3),:])
117
+    dataTest.append(dataframe[i].values[int(dataframe[i].shape[0]*2/3):,:])
118
+
119
+# Calculate means and stdev
120
+a=dataTrain[0]
121
+for i in range(1,NumberOfFailures+1):
122
+    a=np.vstack((a,dataTrain[i]))
123
+
124
+means=a.mean(axis=0) 
125
+stdevs=a.std(axis=0)
126
+def normalize2(train,test):
127
+    return( (train-means)/stdevs, (test-means)/stdevs )
128
+
129
+dataTrainNorm=[]
130
+dataTestNorm=[]
131
+for i in range(NumberOfFailures+1):
132
+    dataTrainNorm.append([])
133
+    dataTestNorm.append([])
134
+
135
+for i in range(NumberOfFailures+1):
136
+    (dataTrainNorm[i],dataTestNorm[i])=normalize2(dataTrain[i],dataTest[i])
137
+
138
+def plotData():    
139
+    fig, axes = plt.subplots(
140
+        nrows=NumberOfFailures+1, ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
141
+    )
142
+    for i in range(NumberOfFailures+1):
143
+        axes[i][0].plot(np.concatenate((dataTrainNorm[i][:,0],dataTestNorm[i][:,0])),label="Fail "+str(i)+",  feature 0")
144
+        axes[i][1].plot(np.concatenate((dataTrainNorm[i][:,1],dataTestNorm[i][:,1])),label="Fail "+str(i)+",  feature 1")
145
+    #axes[1].legend()
146
+    #axes[0].set_ylabel(features[0])
147
+    #axes[1].set_ylabel(features[1])
148
+    plt.show()
149
+
150
+#plotData()
151
+
152
+def create_sequences(values, time_steps):
153
+    output = []
154
+    for i in range(len(values) - time_steps + 1):
155
+        output.append(values[i : (i + time_steps)])
156
+    return np.stack(output)
157
+
158
+def listToString(l):
159
+    r=''
160
+    for i in l:
161
+        r+=str(i)
162
+    return(r.replace(' ',''))
163
+
164
+timesteps=int(options.timesteps)
165
+x_train=[]
166
+for i in range(NumberOfFailures+1):
167
+    x_train.append(create_sequences(dataTrainNorm[i],timesteps))
168
+
169
+xtrain=x_train[0]
170
+for i in range(1,NumberOfFailures+1):
171
+    xtrain=np.vstack((xtrain,x_train[i]))
172
+
173
+km = TimeSeriesKMeans(n_clusters=NumberOfFailures+1, metric="dtw")
174
+modelpath="model_co_unsupervised_"+str(timesteps)+listToString(features)+".pk"
175
+if options.train:
176
+    km.fit(xtrain)
177
+    km.to_pickle(modelpath)
178
+else:
179
+    km.from_pickle(modelpath)
180
+    km.fit_predict(xtrain)
181
+
182
+colorline=['violet','lightcoral','cyan','lime','grey']
183
+colordot=['darkviolet','red','blue','green','black']
184
+
185
+
186
+Ranges=[]
187
+r=0
188
+for i in range(NumberOfFailures+1):
189
+    Ranges.append([r,r+x_train[i].shape[0]])
190
+    r+=x_train[i].shape[0]
191
+# Drop the last TIME_STEPS for plotting
192
+Ranges[NumberOfFailures][1]=Ranges[NumberOfFailures][1]
193
+
194
+featuresToPlot=features
195
+indexesToPlot=[]
196
+for i in featuresToPlot:
197
+    indexesToPlot.append(features.index(i))
198
+
199
+labels=[]    #   Labels are assigned randomly by classifer
200
+for i in range(NumberOfFailures+1):
201
+    b=Counter(km.labels_[Ranges[i][0]:Ranges[i][1]])
202
+    labels.append(b.most_common(1)[0][0])
203
+
204
+
205
+def plot(data,ranges,labels):
206
+    NumFeaturesToPlot=len(indexesToPlot)
207
+    plt.rcParams.update({'font.size': 16})
208
+    fig, axes = plt.subplots(
209
+        nrows=NumFeaturesToPlot, ncols=1, figsize=(15, 10), dpi=80, facecolor="w", edgecolor="k",sharex=True
210
+    )
211
+    for i in range(NumFeaturesToPlot):
212
+        init=0
213
+        end=ranges[0][1]
214
+        for j in range(NumberOfFailures+1):
215
+            axes[i].plot(range(init,end),data[ranges[j][0]:ranges[j][1],0,indexesToPlot[i]]*stdevs[i]+means[i],label="Class "+str(j), color=colorline[j],linewidth=1)
216
+            if j<NumberOfFailures:
217
+                init=end
218
+                end+=(ranges[j+1][1]-ranges[j+1][0])
219
+
220
+        x=[]
221
+        y=[]
222
+        for j in range(NumberOfFailures+1):
223
+            x.append([])
224
+            y.append([])
225
+
226
+        for j in range(NumberOfFailures+1):
227
+            for k in range(ranges[j][0],ranges[j][1]):
228
+                print(j,k)
229
+                x[labels.index(km.labels_[k])].append(k)
230
+                y[labels.index(km.labels_[k])].append(data[k,0,indexesToPlot[i]]*stdevs[i]+means[i])
231
+
232
+        for j in range(NumberOfFailures+1):
233
+            axes[i].plot(x[j],y[j] ,color=colordot[j],marker='.',linewidth=0,label="Class type "+str(j) )
234
+
235
+
236
+        if i==(NumFeatures-1):
237
+            axes[i].legend(loc='right')
238
+        s=''
239
+        s+=featureNames[features[indexesToPlot[i]]]
240
+        s+=' '+unitNames[features[indexesToPlot[i]]]
241
+        axes[i].set_ylabel(s)
242
+        axes[i].grid()
243
+
244
+    axes[NumFeaturesToPlot-1].set_xlabel("Sample number")
245
+    plt.show()
246
+        
247
+   
248
+
249
+#plot(xtrain,Ranges,labels)
250
+
251
+
252
+# Try with test data
253
+
254
+x_test=[]
255
+for i in range(NumberOfFailures+1):
256
+    x_test.append(create_sequences(dataTestNorm[i],timesteps))
257
+
258
+xtest=x_test[0]
259
+for i in range(1,NumberOfFailures+1):
260
+    xtest=np.vstack((xtest,x_test[i]))
261
+
262
+Ranges=[]
263
+r=0
264
+for i in range(NumberOfFailures+1):
265
+    Ranges.append([r,r+x_test[i].shape[0]])
266
+    r+=x_test[i].shape[0]
267
+# Drop the last TIME_STEPS for plotting
268
+Ranges[NumberOfFailures][1]=Ranges[NumberOfFailures][1]
269
+
270
+
271
+km.fit_predict(xtest)
272
+
273
+labels=[]    #   Labels are assigned randomly by classifer
274
+for i in range(NumberOfFailures+1):
275
+    b=Counter(km.labels_[Ranges[i][0]:Ranges[i][1]])
276
+    labels.append(b.most_common(1)[0][0])
277
+
278
+plot(xtest,Ranges,labels)
279
+

+ 329
- 0
v1_unsupervised.py Ver arquivo

@@ -0,0 +1,329 @@
1
+# Csar Fdez, UdL, 2025
2
+#  Unsupervised classification. Uses tslearn
3
+#  https://tslearn.readthedocs.io/en/stable/index.html
4
+
5
+# Be careful with v0_unsupervised  and all versions for supervised.
6
+# because dataTrain is not stacke before create_sequences,  so, 
7
+#  the sets are not aligned in time
8
+
9
+
10
+import pandas as pd
11
+import matplotlib.pyplot as plt
12
+import datetime
13
+import numpy as np
14
+import os.path
15
+from optparse import OptionParser
16
+import copy
17
+import pickle
18
+from tslearn.clustering import TimeSeriesKMeans
19
+from collections import Counter
20
+
21
+parser = OptionParser()
22
+parser.add_option("-t", "--train", dest="train", help="Trains the models (false)", default=False, action="store_true")
23
+parser.add_option("-n", "--timesteps", dest="timesteps", help="TIME STEPS ", default=12)
24
+
25
+(options, args) = parser.parse_args()
26
+
27
+
28
+# data files arrays. Index:
29
+# 0.  No failure
30
+# 1.  Blocked evaporator
31
+# 2.   Full Blocked condenser
32
+# 3.   Partial Blocked condenser
33
+# 4   Fan condenser not working
34
+# 5.  Open door
35
+
36
+
37
+NumberOfFailures=4  # So far, we have only data for the first 4 types of failures
38
+datafiles=[]
39
+for i in range(NumberOfFailures+1):
40
+    datafiles.append([])
41
+
42
+# Next set of ddata corresponds to Freezer, SP=-26
43
+datafiles[0]=['2024-08-07_5_','2024-08-08_5_','2025-01-25_5_','2025-01-26_5_','2025-01-27_5_','2025-01-28_5_'] 
44
+datafiles[1]=['2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_'] 
45
+#datafiles[1]=['2024-12-17_5_','2024-12-16_5_','2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_'] #   This have transitions
46
+datafiles[2]=['2024-12-18_5_','2024-12-19_5_'] 
47
+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_'] 
48
+datafiles[4]=['2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_'] 
49
+#datafiles[4]=['2024-12-27_5_','2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_']  #   This have transitions
50
+
51
+#datafiles[4]=[] 
52
+
53
+# Features suggested by Xavier
54
+# Care with 'tc s3' because on datafiles[0] is always nulll
55
+# Seems to be incoropored in new tests
56
+
57
+#r1s5 supply air flow temperature
58
+#r1s1 inlet evaporator temperature
59
+#r1s4 condenser outlet
60
+
61
+# VAriables r1s4 and pa1 apiii  may not exists in cloud controlers
62
+
63
+
64
+features=['r1 s1','r1 s4','r1 s5','pa1 apiii']
65
+features=['r1 s1','r1 s4','r1 s5']
66
+featureNames={}
67
+featureNames['r1 s1']='$T_{evap}$'
68
+featureNames['r1 s4']='$T_{cond}$'
69
+featureNames['r1 s5']='$T_{air}$'
70
+featureNames['pa1 apiii']='$P_{elec}$'
71
+
72
+unitNames={}
73
+unitNames['r1 s1']='$(^{o}C)$'
74
+unitNames['r1 s4']='$(^{o}C)$'
75
+unitNames['r1 s5']='$(^{o}C)$'
76
+unitNames['pa1 apiii']='$(W)$'
77
+
78
+
79
+#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']
80
+
81
+#features=['r2 s2', 'tc s1','r1 s10','r1 s6','r2 s8']
82
+
83
+NumFeatures=len(features)
84
+
85
+df_list=[]
86
+for i in range(NumberOfFailures+1):
87
+    df_list.append([])
88
+
89
+for i in range(NumberOfFailures+1):
90
+    dftemp=[]
91
+    for f in datafiles[i]:
92
+        print("                 ", f)
93
+        #df1 = pd.read_csv('./data/'+f+'.csv', parse_dates=['datetime'], dayfirst=True, index_col='datetime')
94
+        df1 = pd.read_csv('./data/'+f+'.csv')
95
+        dftemp.append(df1)
96
+    df_list[i]=pd.concat(dftemp)
97
+
98
+
99
+# subsampled to 5'  =  30 * 10"
100
+# We consider smaples every 5' because in production, we will only have data at this frequency
101
+subsamplingrate=30
102
+
103
+dataframe=[]
104
+for i in range(NumberOfFailures+1):
105
+    dataframe.append([])
106
+
107
+for i in range(NumberOfFailures+1):
108
+    datalength=df_list[i].shape[0]
109
+    dataframe[i]=df_list[i].iloc[range(0,datalength,subsamplingrate)][features]
110
+    dataframe[i].reset_index(inplace=True,drop=True)
111
+    dataframe[i].dropna(inplace=True)
112
+
113
+
114
+# Train data is first 2/3 of data
115
+# Test data is: last 1/3 of data 
116
+dataTrain=[]
117
+dataTest=[]
118
+for i in range(NumberOfFailures+1):
119
+    dataTrain.append(dataframe[i].values[0:int(dataframe[i].shape[0]*2/3),:])
120
+    dataTest.append(dataframe[i].values[int(dataframe[i].shape[0]*2/3):,:])
121
+
122
+# Calculate means and stdev
123
+a=dataTrain[0]
124
+for i in range(1,NumberOfFailures+1):
125
+    a=np.vstack((a,dataTrain[i]))
126
+
127
+means=a.mean(axis=0) 
128
+stdevs=a.std(axis=0)
129
+def normalize2(train,test):
130
+    return( (train-means)/stdevs, (test-means)/stdevs )
131
+
132
+dataTrainNorm=[]
133
+dataTestNorm=[]
134
+for i in range(NumberOfFailures+1):
135
+    dataTrainNorm.append([])
136
+    dataTestNorm.append([])
137
+
138
+for i in range(NumberOfFailures+1):
139
+    (dataTrainNorm[i],dataTestNorm[i])=normalize2(dataTrain[i],dataTest[i])
140
+
141
+def plotData():    
142
+    fig, axes = plt.subplots(
143
+        nrows=NumberOfFailures+1, ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
144
+    )
145
+    for i in range(NumberOfFailures+1):
146
+        axes[i][0].plot(np.concatenate((dataTrainNorm[i][:,0],dataTestNorm[i][:,0])),label="Fail "+str(i)+",  feature 0")
147
+        axes[i][1].plot(np.concatenate((dataTrainNorm[i][:,1],dataTestNorm[i][:,1])),label="Fail "+str(i)+",  feature 1")
148
+    #axes[1].legend()
149
+    #axes[0].set_ylabel(features[0])
150
+    #axes[1].set_ylabel(features[1])
151
+    plt.show()
152
+
153
+#plotData()
154
+
155
+def create_sequences(values, time_steps):
156
+    output = []
157
+    for i in range(len(values) - time_steps ):
158
+        output.append(values[i : (i + time_steps)])
159
+    return np.stack(output)
160
+
161
+def listToString(l):
162
+    r=''
163
+    for i in l:
164
+        r+=str(i)
165
+    return(r.replace(' ',''))
166
+
167
+timesteps=int(options.timesteps)
168
+
169
+X=dataTrainNorm[0]
170
+for i in range(1,NumberOfFailures+1):
171
+    X=np.vstack((X,dataTrainNorm[i]))
172
+
173
+xtrain=create_sequences(X,timesteps)
174
+
175
+km = TimeSeriesKMeans(n_clusters=NumberOfFailures+1, metric="dtw")
176
+modelpath="model_v1_unsupervised_"+str(timesteps)+listToString(features)+".pk"
177
+if options.train:
178
+    km.fit(xtrain)
179
+    km.to_pickle(modelpath)
180
+else:
181
+    km.from_pickle(modelpath)
182
+    #km.fit_predict(xtrain)
183
+
184
+colorline=['violet','lightcoral','cyan','lime','grey']
185
+colordot=['darkviolet','red','blue','green','black']
186
+
187
+
188
+
189
+
190
+
191
+featuresToPlot=features
192
+indexesToPlot=[]
193
+for i in featuresToPlot:
194
+    indexesToPlot.append(features.index(i))
195
+
196
+
197
+def plot(data,ranges):
198
+
199
+    km.fit_predict(data)
200
+# Expand data to plot with the timesteps samples of last sample
201
+    datatoplot=data[:,0,:]
202
+    datatoplot=np.vstack((datatoplot,data[ranges[len(ranges)-1][1],:,:]))
203
+
204
+    labels=[]    #   Labels are assigned randomly by classifer
205
+    for i in range(len(ranges)):
206
+        b=Counter(km.labels_[ranges[i][0]:ranges[i][1]])
207
+        labels.append(b.most_common(1)[0][0])
208
+
209
+    print("\n\n\n\LABELS: ",labels,"\n\n")
210
+
211
+    NumFeaturesToPlot=len(indexesToPlot)
212
+    plt.rcParams.update({'font.size': 16})
213
+    fig, axes = plt.subplots(
214
+        nrows=NumFeaturesToPlot, ncols=1, figsize=(15, 10), dpi=80, facecolor="w", edgecolor="k",sharex=True
215
+    )
216
+    for i in range(NumFeaturesToPlot):
217
+        init=0
218
+        end=ranges[0][1]
219
+        labelsplotted=[]
220
+        for j in range(len(ranges)):
221
+            if j==(len(ranges)-1): # Plot the last timesteps
222
+                classtype=labels.index(labels[j])
223
+                if classtype in labelsplotted:
224
+                    axes[i].plot(range(init,end+timesteps),datatoplot[ranges[j][0]:ranges[j][1]+timesteps,indexesToPlot[i]]*stdevs[i]+means[i], color=colorline[classtype],linewidth=1)
225
+                else:
226
+                    axes[i].plot(range(init,end+timesteps),datatoplot[ranges[j][0]:ranges[j][1]+timesteps,indexesToPlot[i]]*stdevs[i]+means[i], label="Class: "+str(classtype), color=colorline[classtype],linewidth=1)
227
+                    labelsplotted.append(classtype)
228
+            else:
229
+                classtype=labels.index(labels[j])
230
+                if classtype in labelsplotted:
231
+                    axes[i].plot(range(init,end),datatoplot[ranges[j][0]:ranges[j][1],indexesToPlot[i]]*stdevs[i]+means[i], color=colorline[classtype],linewidth=1)
232
+                else:
233
+                    axes[i].plot(range(init,end),datatoplot[ranges[j][0]:ranges[j][1],indexesToPlot[i]]*stdevs[i]+means[i], label="Class: "+str(classtype), color=colorline[classtype],linewidth=1)
234
+                    labelsplotted.append(classtype)
235
+            init=end
236
+            if j<(len(ranges)-1):
237
+                end+=(ranges[j+1][1]-ranges[j+1][0])
238
+        x=[]
239
+        y=[]
240
+        for j in range(len(ranges)):
241
+            x.append([])
242
+            y.append([])
243
+
244
+        for j in range(len(ranges)):
245
+            for k in range(ranges[j][0],ranges[j][1]):
246
+                try:  # Idont know why sometimes fails index !!!!
247
+                    x[labels.index(km.labels_[k])].append(k+timesteps)
248
+                    y[labels.index(km.labels_[k])].append(datatoplot[k+timesteps,indexesToPlot[i]]*stdevs[i]+means[i])
249
+                except:
250
+                    x[0].append(k+timesteps)
251
+                    y[0].append(datatoplot[k+timesteps,indexesToPlot[i]]*stdevs[i]+means[i])
252
+
253
+        labelsplotted=[]
254
+        for j in range(len(ranges)):
255
+            classtype=labels.index(labels[j])
256
+            if classtype in labelsplotted:
257
+                axes[i].plot(x[j],y[j] ,color=colordot[labels.index(labels[j])],marker='.',linewidth=0)
258
+            else:
259
+                axes[i].plot(x[j],y[j] ,color=colordot[labels.index(labels[j])],marker='.',linewidth=0,label="Class type "+str(j) )
260
+                labelsplotted.append(classtype)
261
+
262
+        if i==(NumFeatures-1):
263
+            axes[i].legend(loc='right')
264
+        s=''
265
+        s+=featureNames[features[indexesToPlot[i]]]
266
+        s+=' '+unitNames[features[indexesToPlot[i]]]
267
+        axes[i].set_ylabel(s)
268
+        axes[i].grid()
269
+
270
+    axes[NumFeaturesToPlot-1].set_xlabel("Sample number")
271
+    plt.show()
272
+        
273
+   
274
+'''
275
+Ranges=[]
276
+r=0
277
+for i in range(NumberOfFailures+1):
278
+    Ranges.append([r,r+dataTrainNorm[i].shape[0]])
279
+    r+=dataTrainNorm[i].shape[0]
280
+# Drop the last TIME_STEPS for plotting
281
+Ranges[NumberOfFailures][1]=Ranges[NumberOfFailures][1]-timesteps-1
282
+
283
+plot(xtrain,Ranges)
284
+'''
285
+# Try with test data
286
+X=dataTestNorm[0]
287
+Ranges=[[0,dataTestNorm[0].shape[0]]]
288
+r=dataTestNorm[0].shape[0]
289
+for i in range(1,NumberOfFailures+1):
290
+    X=np.vstack((X,dataTestNorm[i]))
291
+    Ranges.append([r,r+dataTestNorm[i].shape[0]])
292
+    r+=dataTestNorm[i].shape[0]
293
+
294
+X=np.vstack((X,dataTestNorm[0]))  # We add a last segment of no fail data
295
+Ranges.append([r,r+dataTestNorm[0].shape[0]])
296
+Ranges[len(Ranges)-1][1]=Ranges[len(Ranges)-1][1]-timesteps-1
297
+
298
+xtest=create_sequences(X,timesteps)
299
+
300
+
301
+
302
+km.fit_predict(xtest)
303
+plot(xtest,Ranges)
304
+
305
+exit(0)
306
+def anomalyMetric(labels,ranges):
307
+    # FP, TP: false/true positive
308
+    # TN, FN: true/false negative
309
+    # Sensitivity (recall): probab failure detection if data is fail: TP/(TP+FN)
310
+    # Precision: Rate of positive results:  TP/(TP+FP)  
311
+    # F1-score: predictive performance measure: 2*Precision*Sensitity/(Precision+Sensitity)
312
+
313
+    lab=[]    #   Labels are assigned randomly by classifer
314
+    TP=[]
315
+    for i in range(NumberOfFailures+1):
316
+        TP.append([])
317
+        b=Counter(labels[ranges[i][0]:ranges[i][1]])
318
+        lab.append(b.most_common(1)[0][0])
319
+
320
+    print(lab)
321
+    #for i in range(NumberOfFailures+1):
322
+
323
+
324
+
325
+
326
+anomalyMetric(km.labels_,Ranges)
327
+
328
+
329
+

+ 475
- 0
v3_class.py Ver arquivo

@@ -0,0 +1,475 @@
1
+# Csar Fdez, UdL, 2025
2
+# Changes from v1:   Normalization 
3
+# IN v1, each failure type has its own normalization pars (mean and stdevs)
4
+# In v2, mean and stdev is the same for all data
5
+# v3.py trains the models looping in TIME_STEPS (4,8,12,16,20,24,....) finding the optimal Threshold factor
6
+
7
+#  Derived from v3.py with code from v1_multifailure.py
8
+#  This code don't train for multiple time steps !!
9
+
10
+import pandas as pd
11
+import matplotlib.pyplot as plt
12
+import datetime
13
+import numpy as np
14
+import keras
15
+import os.path
16
+from keras import layers
17
+from optparse import OptionParser
18
+import copy
19
+import pickle
20
+
21
+
22
+parser = OptionParser()
23
+parser.add_option("-t", "--train", dest="train", help="Trains the models (false)", default=False, action="store_true")
24
+parser.add_option("-n", "--timesteps", dest="timesteps", help="TIME STEPS ", default=12)
25
+parser.add_option("-f", "--thresholdfactor", dest="TF", help="Threshold Factor ", default=1.4)
26
+
27
+(options, args) = parser.parse_args()
28
+
29
+
30
+# data files arrays. Index:
31
+# 0.  No failure
32
+# 1.  Blocked evaporator
33
+# 2.   Full Blocked condenser
34
+# 3.   Partial Blocked condenser
35
+# 4   Fan condenser not working
36
+# 5.  Open door
37
+
38
+
39
+NumberOfFailures=4  # So far, we have only data for the first 4 types of failures
40
+datafiles=[]
41
+for i in range(NumberOfFailures+1):
42
+    datafiles.append([])
43
+
44
+# Next set of ddata corresponds to Freezer, SP=-26
45
+datafiles[0]=['2024-08-07_5_','2024-08-08_5_','2025-01-25_5_','2025-01-26_5_','2025-01-27_5_','2025-01-28_5_'] 
46
+datafiles[1]=['2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_'] 
47
+#datafiles[1]=['2024-12-17_5_','2024-12-16_5_','2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_'] #   This have transitions
48
+datafiles[2]=['2024-12-18_5_','2024-12-19_5_'] 
49
+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_'] 
50
+datafiles[4]=['2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_'] 
51
+#datafiles[4]=['2024-12-27_5_','2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_']  #   This have transitions
52
+
53
+#datafiles[4]=[] 
54
+
55
+# Features suggested by Xavier
56
+# Care with 'tc s3' because on datafiles[0] is always nulll
57
+# Seems to be incoropored in new tests
58
+
59
+#r1s5 supply air flow temperature
60
+#r1s1 inlet evaporator temperature
61
+#r1s4 condenser outlet
62
+
63
+# VAriables r1s4 and pa1 apiii  may not exists in cloud controlers
64
+
65
+
66
+features=['r1 s1','r1 s4','r1 s5','pa1 apiii']
67
+features=['r1 s1','r1 s4','r1 s5']
68
+featureNames={}
69
+featureNames['r1 s1']='$T_{evap}$'
70
+featureNames['r1 s4']='$T_{cond}$'
71
+featureNames['r1 s5']='$T_{air}$'
72
+featureNames['pa1 apiii']='$P_{elec}$'
73
+
74
+unitNames={}
75
+unitNames['r1 s1']='$(^{o}C)$'
76
+unitNames['r1 s4']='$(^{o}C)$'
77
+unitNames['r1 s5']='$(^{o}C)$'
78
+unitNames['pa1 apiii']='$(W)$'
79
+
80
+
81
+#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']
82
+
83
+#features=['r2 s2', 'tc s1','r1 s10','r1 s6','r2 s8']
84
+
85
+NumFeatures=len(features)
86
+
87
+df_list=[]
88
+for i in range(NumberOfFailures+1):
89
+    df_list.append([])
90
+
91
+for i in range(NumberOfFailures+1):
92
+    dftemp=[]
93
+    for f in datafiles[i]:
94
+        print("                 ", f)
95
+        #df1 = pd.read_csv('./data/'+f+'.csv', parse_dates=['datetime'], dayfirst=True, index_col='datetime')
96
+        df1 = pd.read_csv('./data/'+f+'.csv')
97
+        dftemp.append(df1)
98
+    df_list[i]=pd.concat(dftemp)
99
+
100
+
101
+# subsampled to 5'  =  30 * 10"
102
+# We consider smaples every 5' because in production, we will only have data at this frequency
103
+subsamplingrate=30
104
+
105
+dataframe=[]
106
+for i in range(NumberOfFailures+1):
107
+    dataframe.append([])
108
+
109
+for i in range(NumberOfFailures+1):
110
+    datalength=df_list[i].shape[0]
111
+    dataframe[i]=df_list[i].iloc[range(0,datalength,subsamplingrate)][features]
112
+    dataframe[i].reset_index(inplace=True,drop=True)
113
+    dataframe[i].dropna(inplace=True)
114
+
115
+
116
+# Train data is first 2/3 of data
117
+# Test data is: last 1/3 of data 
118
+dataTrain=[]
119
+dataTest=[]
120
+for i in range(NumberOfFailures+1):
121
+    dataTrain.append(dataframe[i].values[0:int(dataframe[i].shape[0]*2/3),:])
122
+    dataTest.append(dataframe[i].values[int(dataframe[i].shape[0]*2/3):,:])
123
+
124
+# Calculate means and stdev
125
+a=dataTrain[0]
126
+for i in range(1,NumberOfFailures+1):
127
+    a=np.vstack((a,dataTrain[i]))
128
+
129
+means=a.mean(axis=0) 
130
+stdevs=a.std(axis=0)
131
+def normalize2(train,test):
132
+    return( (train-means)/stdevs, (test-means)/stdevs )
133
+
134
+dataTrainNorm=[]
135
+dataTestNorm=[]
136
+for i in range(NumberOfFailures+1):
137
+    dataTrainNorm.append([])
138
+    dataTestNorm.append([])
139
+
140
+for i in range(NumberOfFailures+1):
141
+    (dataTrainNorm[i],dataTestNorm[i])=normalize2(dataTrain[i],dataTest[i])
142
+
143
+def plotData():    
144
+    fig, axes = plt.subplots(
145
+        nrows=NumberOfFailures+1, ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
146
+    )
147
+    for i in range(NumberOfFailures+1):
148
+        axes[i][0].plot(np.concatenate((dataTrainNorm[i][:,0],dataTestNorm[i][:,0])),label="Fail "+str(i)+",  feature 0")
149
+        axes[i][1].plot(np.concatenate((dataTrainNorm[i][:,1],dataTestNorm[i][:,1])),label="Fail "+str(i)+",  feature 1")
150
+    #axes[1].legend()
151
+    #axes[0].set_ylabel(features[0])
152
+    #axes[1].set_ylabel(features[1])
153
+    plt.show()
154
+
155
+#plotData()
156
+#exit(0)
157
+
158
+
159
+NumFilters=64
160
+KernelSize=7
161
+DropOut=0.2
162
+ThresholdFactor=1.4
163
+def create_sequences(values, time_steps):
164
+    output = []
165
+    for i in range(len(values) - time_steps + 1):
166
+        output.append(values[i : (i + time_steps)])
167
+    return np.stack(output)
168
+
169
+def AtLeastOneTrue(x):
170
+    for i in range(NumFeatures):
171
+        if x[i]:
172
+            return True
173
+    return False
174
+
175
+def anomalyMetric(th,ts,testList):  # first of list is non failure data
176
+    # FP, TP: false/true positive
177
+    # TN, FN: true/false negative
178
+    # Sensitivity (recall): probab failure detection if data is fail: TP/(TP+FN)
179
+    # Specificity: true negative ratio given  data is OK: TN/(TN+FP)
180
+    # Accuracy: Rate of correct predictions:  (TN+TP)/(TN+TP+FP+FN)
181
+    # Precision: Rate of positive results:  TP/(TP+FP)  
182
+    # F1-score: predictive performance measure: 2*Precision*Sensitity/(Precision+Sensitity)
183
+    # F2-score: predictive performance measure:  2*Specificity*Sensitity/(Specificity+Sensitity)
184
+
185
+    x_test = create_sequences(testList[0],ts)
186
+    x_test_pred = model.predict(x_test)
187
+    test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
188
+    anomalies = test_mae_loss > th
189
+    count=0
190
+    for i in range(anomalies.shape[0]):
191
+        if AtLeastOneTrue(anomalies[i]):
192
+            count+=1
193
+    FP=count
194
+    TN=anomalies.shape[0]-count
195
+    count=0
196
+    TP=np.zeros((NumberOfFailures))
197
+    FN=np.zeros((NumberOfFailures))
198
+    Sensitivity=np.zeros((NumberOfFailures))
199
+    Precision=np.zeros((NumberOfFailures))
200
+    for i in range(1,len(testList)):
201
+        x_test = create_sequences(testList[i],ts)
202
+        x_test_pred = model.predict(x_test)
203
+        test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
204
+        anomalies = test_mae_loss > th
205
+        count=0
206
+        for j in range(anomalies.shape[0]):
207
+            if AtLeastOneTrue(anomalies[j]):
208
+                count+=1
209
+        TP[i-1] = count
210
+        FN[i-1] = anomalies.shape[0]-count
211
+        Sensitivity[i-1]=TP[i-1]/(TP[i-1]+FN[i-1])
212
+        Precision[i-1]=TP[i-1]/(TP[i-1]+FP)
213
+
214
+    GlobalSensitivity=TP.sum()/(TP.sum()+FN.sum())
215
+    Specificity=TN/(TN+FP)
216
+    Accuracy=(TN+TP.sum())/(TN+TP.sum()+FP+FN.sum())
217
+    GlobalPrecision=TP.sum()/(TP.sum()+FP)
218
+    F1Score= 2*GlobalPrecision*GlobalSensitivity/(GlobalPrecision+GlobalSensitivity)
219
+    F2Score = 2*Specificity*GlobalSensitivity/(Specificity+GlobalSensitivity)
220
+
221
+    print("Sensitivity: ",Sensitivity)
222
+    print("Global Sensitivity: ",GlobalSensitivity)
223
+    #print("Precision: ",Precision)
224
+    #print("Global Precision: ",GlobalPrecision)
225
+    print("Specifity: ",Specificity)
226
+    #print("Accuracy: ",Accuracy)
227
+    #print("F1Score: ",F1Score)
228
+    print("F2Score: ",F2Score)
229
+    #print("FP: ",FP)
230
+    #return Sensitivity+Specifity
231
+    return F2Score
232
+
233
+def listToString(l):
234
+    r=''
235
+    for i in l:
236
+        r+=str(i)
237
+    return(r.replace(' ',''))
238
+
239
+threshold={} 
240
+
241
+fname='threshold_class'+listToString(features)+'.pk'
242
+if os.path.isfile(fname):  # Checks if it's a file and exists
243
+    print("File ",fname," exists. Loading it!")
244
+    file = open(fname, 'rb')
245
+    threshold=pickle.load(file)
246
+    file.close()
247
+    if not int(options.timesteps) in threshold.keys():
248
+        threshold[int(options.timesteps)]=[]
249
+        for i in range(NumberOfFailures+1):
250
+            threshold[int(options.timesteps)].append(0) # Initzialize
251
+else:
252
+    threshold[int(options.timesteps)]=[]
253
+    for i in range(NumberOfFailures+1):
254
+        threshold[int(options.timesteps)].append(0) # Initzialize
255
+
256
+
257
+model=[]
258
+modelckpt_callback =[]
259
+es_callback =[]
260
+path_checkpoint=[]
261
+
262
+timesteps=int(options.timesteps)
263
+x_train=[]
264
+for i in range(NumberOfFailures+1):
265
+    x_train.append(create_sequences(dataTrainNorm[i],timesteps))
266
+    model.append([])
267
+    model[i] = keras.Sequential(
268
+        [
269
+            layers.Input(shape=(x_train[i].shape[1], x_train[i].shape[2])),
270
+            layers.Conv1D(
271
+                filters=NumFilters,
272
+                kernel_size=KernelSize,
273
+                padding="same",
274
+                strides=2,
275
+                activation="relu",
276
+            ),
277
+            layers.Dropout(rate=DropOut),
278
+            layers.Conv1D(
279
+                filters=int(NumFilters/2),
280
+                kernel_size=KernelSize,
281
+                padding="same",
282
+                strides=2,
283
+                activation="relu",
284
+            ),
285
+            layers.Conv1DTranspose(
286
+                filters=int(NumFilters/2),
287
+                kernel_size=KernelSize,
288
+                padding="same",
289
+                strides=2,
290
+                activation="relu",
291
+            ),
292
+            layers.Dropout(rate=DropOut),
293
+            layers.Conv1DTranspose(
294
+                filters=NumFilters,
295
+                kernel_size=KernelSize,
296
+                padding="same",
297
+                strides=2,
298
+                activation="relu",
299
+            ),
300
+            layers.Conv1DTranspose(filters=x_train[i].shape[2], kernel_size=KernelSize, padding="same"),
301
+        ]
302
+    )
303
+    model[i].compile(optimizer=keras.optimizers.Adam(learning_rate=0.001), loss="mse")
304
+    model[i].summary()
305
+    path_checkpoint.append("model_class_v3_"+str(i)+"_"+str(timesteps)+listToString(features)+"_checkpoint.weights.h5")
306
+    es_callback.append(keras.callbacks.EarlyStopping(monitor="val_loss", min_delta=0, patience=15))
307
+    modelckpt_callback.append(keras.callbacks.ModelCheckpoint( monitor="val_loss", filepath=path_checkpoint[i], verbose=1, save_weights_only=True, save_best_only=True,))
308
+
309
+
310
+if options.train:
311
+    history=[]    
312
+    for i in range(NumberOfFailures+1):
313
+        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]      ],))
314
+
315
+        x_train_pred=model[i].predict(x_train[i])
316
+        train_mae_loss=np.mean(np.abs(x_train_pred - x_train[i]), axis=1)
317
+        threshold[timesteps][i]=np.max(train_mae_loss,axis=0)
318
+
319
+    file = open('threshold_class'+listToString(features)+'.pk', 'wb')
320
+    pickle.dump(threshold, file)
321
+    file.close()
322
+else:
323
+    for i in range(NumberOfFailures+1):
324
+        model[i].load_weights(path_checkpoint[i])
325
+
326
+file = open('threshold_class'+listToString(features)+'.pk', 'rb')
327
+threshold=pickle.load(file)
328
+file.close()
329
+#print(threshold)   
330
+
331
+#  1st scenario. Detect only anomaly.  Later, we will classiffy it
332
+# Test data=  testnormal + testfail1 + testtail2 + testfail3 + testfail4 + testnormal
333
+datalist=[dataTestNorm[0],dataTestNorm[1],dataTestNorm[2],dataTestNorm[3],dataTestNorm[4]]
334
+d=np.vstack((datalist))
335
+
336
+x_test = create_sequences(d,int(options.timesteps))
337
+x_test_pred = model[0].predict(x_test)
338
+test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
339
+anomalies = test_mae_loss > threshold[int(options.timesteps)][0]*float(options.TF)
340
+anomalous_data_indices = []
341
+for i in range(anomalies.shape[0]):
342
+    if AtLeastOneTrue(anomalies[i]):
343
+    #if anomalies[i][0] or anomalies[i][1] or anomalies[i][2] or anomalies[i][3]:
344
+        anomalous_data_indices.append(i)
345
+
346
+# Define ranges for plotting in different colors
347
+testRanges=[]
348
+r=0
349
+for i in range(len(datalist)):
350
+    testRanges.append([r,r+datalist[i].shape[0]])
351
+    r+=datalist[i].shape[0]
352
+# Drop the last TIME_STEPS for plotting
353
+testRanges[NumberOfFailures][1]=testRanges[NumberOfFailures][1]-int(options.timesteps)
354
+
355
+# Let's plot some features
356
+
357
+colorline=['violet','lightcoral','cyan','lime','grey']
358
+colordot=['darkviolet','red','blue','green','black']
359
+
360
+#featuresToPlot=['r1 s1','r1 s2','r1 s3','pa1 apiii']
361
+featuresToPlot=features
362
+
363
+indexesToPlot=[]
364
+for i in featuresToPlot:
365
+    indexesToPlot.append(features.index(i))
366
+
367
+def plotData3():
368
+    NumFeaturesToPlot=len(indexesToPlot)
369
+    plt.rcParams.update({'font.size': 16})
370
+    fig, axes = plt.subplots(
371
+        nrows=NumFeaturesToPlot, ncols=1, figsize=(15, 10), dpi=80, facecolor="w", edgecolor="k",sharex=True
372
+    )
373
+    for i in range(NumFeaturesToPlot):
374
+        x=[]
375
+        y=[]
376
+        for k in anomalous_data_indices:
377
+            if (k+int(options.timesteps))<x_test.shape[0]:
378
+                x.append(k+int(options.timesteps))
379
+                y.append(x_train[k+int(options.timesteps),0,indexesToPlot[i]]*stdevs[i]+means[i])
380
+        axes[i].plot(x,y ,color='black',marker='.',linewidth=0,label="Fail detection" )
381
+
382
+
383
+        init=0
384
+        end=testRanges[0][1]
385
+        axes[i].plot(range(init,end),xtrain[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]]*stdevs[i]+means[i],label="No fail")
386
+        init=end
387
+        end+=(testRanges[1][1]-testRanges[1][0])
388
+        for j in range(1,NumberOfFailures+1):
389
+            axes[i].plot(range(init,end),xtrain[testRanges[j][0]:testRanges[j][1],0,indexesToPlot[i]]*stdevs[i]+means[i],label="Fail type "+str(j), color=colorline[j-1],linewidth=1)
390
+            if j<NumberOfFailures:
391
+                init=end
392
+                end+=(testRanges[j+1][1]-testRanges[j+1][0])
393
+
394
+
395
+        if i==(NumFeatures-1):
396
+            axes[i].legend(loc='right')
397
+        s=''
398
+        s+=featureNames[features[indexesToPlot[i]]]
399
+        s+=' '+unitNames[features[indexesToPlot[i]]]
400
+        axes[i].set_ylabel(s)
401
+        axes[i].grid()
402
+    axes[NumFeaturesToPlot-1].set_xlabel("Sample number")
403
+    plt.show()
404
+
405
+
406
+#plotData3()
407
+
408
+
409
+#   2nd scenario. Go over anomalies and classify it by less error
410
+
411
+anomalous_data_type=[]
412
+x_test_predict=[]
413
+for m in range(1,NumberOfFailures+1):
414
+    x_test_predict.append(model[m].predict(x_test))
415
+
416
+anomalous_data_type={}
417
+for i in range(1,NumberOfFailures+1):
418
+    anomalous_data_type[i-1]=[]
419
+
420
+for i in anomalous_data_indices:
421
+    error=[]
422
+    for m in range(1,NumberOfFailures+1):
423
+        error.append(np.mean(np.mean(np.abs(x_test_predict[m-1][i:i+1,:,:]-x_test[i:i+1,:,:]),axis=1)))
424
+    anomalous_data_type[np.argmin(error)].append(i)
425
+
426
+
427
+def plotData4():
428
+    NumFeaturesToPlot=len(indexesToPlot)
429
+    plt.rcParams.update({'font.size': 16})
430
+    fig, axes = plt.subplots(
431
+        nrows=NumFeaturesToPlot, ncols=1, figsize=(15, 10), dpi=80, facecolor="w", edgecolor="k",sharex=True
432
+    )
433
+    for i in range(NumFeaturesToPlot):
434
+
435
+
436
+        init=0
437
+        end=testRanges[0][1]
438
+        axes[i].plot(range(init,end),x_test[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]]*stdevs[i]+means[i],label="No fail", color='black')
439
+        init=end
440
+        end+=(testRanges[1][1]-testRanges[1][0])
441
+        for j in range(1,NumberOfFailures+1):
442
+            axes[i].plot(range(init,end),x_test[testRanges[j][0]:testRanges[j][1],0,indexesToPlot[i]]*stdevs[i]+means[i],label="Fail type "+str(j), color=colorline[j-1],linewidth=1)
443
+            if j<NumberOfFailures:
444
+                init=end
445
+                end+=(testRanges[j+1][1]-testRanges[j+1][0])
446
+
447
+        for j in range(NumberOfFailures):
448
+            x=[]
449
+            y=[]
450
+            for k in anomalous_data_type[j]:
451
+                if (k+int(options.timesteps))<x_test.shape[0]:
452
+                    x.append(k+int(options.timesteps))
453
+                    y.append(x_test[k+int(options.timesteps),0,indexesToPlot[i]]*stdevs[i]+means[i])
454
+            axes[i].plot(x,y ,color=colordot[j],marker='.',linewidth=0,label="Fail detect  type "+str(j+1) )
455
+
456
+
457
+
458
+        if i==(NumFeatures-1):
459
+            axes[i].legend(loc='right')
460
+        s=''
461
+        s+=featureNames[features[indexesToPlot[i]]]
462
+        s+=' '+unitNames[features[indexesToPlot[i]]]
463
+        axes[i].set_ylabel(s)
464
+        axes[i].grid()
465
+    axes[NumFeaturesToPlot-1].set_xlabel("Sample number")
466
+    plt.show()
467
+
468
+
469
+plotData4()
470
+
471
+##   It remains to implemenent anomaly metrics for each failure type
472
+
473
+exit(0)
474
+
475
+

Powered by TurnKey Linux.