Spaces:
Sleeping
Sleeping
Commit
·
d0f2767
1
Parent(s):
f5e1991
Add pickle files for PCA, scaler, and k-means models
Browse files- dashboard.py +138 -59
- mqttpublisher.ipynb +0 -0
- physLSTM/kmeans_vav_2.pkl +3 -0
- physLSTM/lstm_vav_rtu1.ipynb +43 -22
- physLSTM/lstm_vav_rtu2.ipynb +0 -0
- physLSTM/pca_vav_2.pkl +3 -0
- physLSTM/scaler_vav_1.pkl +3 -0
- src/energy_prediction/{EnergyPredictionNorth.py → EnergyPredictionModel.py} +25 -9
- src/energy_prediction/EnergyPredictionPipeline.py +59 -48
- src/energy_prediction/EnergyPredictionSouth.py +0 -0
- src/energy_prediction/models/lstm_energy_south_01.keras +0 -0
- src/energy_prediction/models/scalerSouth.pkl +3 -0
- src/energy_prediction/test_main.py +43 -0
- src/vav/VAVAnomalizer.py +54 -19
- src/vav/VAVPipeline.py +19 -30
- src/vav/models/kmeans_vav_1.pkl +2 -2
- src/vav/models/kmeans_vav_2.pkl +3 -0
- src/vav/models/kmeans_vav_3.pkl +3 -0
- src/vav/models/kmeans_vav_4.pkl +3 -0
- src/vav/models/lstm_vav_02.keras +0 -0
- src/vav/models/lstm_vav_03.keras +0 -0
- src/vav/models/lstm_vav_04.keras +0 -0
- src/vav/models/pca_vav_1.pkl +3 -0
- src/vav/models/pca_vav_2.pkl +3 -0
- {physLSTM → src/vav/models}/scaler_vav_2.pkl +0 -0
- src/vav/models/scaler_vav_3.pkl +3 -0
- src/vav/models/scaler_vav_4.pkl +3 -0
dashboard.py
CHANGED
@@ -1,4 +1,8 @@
|
|
1 |
from collections import deque
|
|
|
|
|
|
|
|
|
2 |
import streamlit as st
|
3 |
import pandas as pd
|
4 |
import numpy as np
|
@@ -13,39 +17,82 @@ rtu_data_pipeline = RTUPipeline(
|
|
13 |
scaler1_path="src/rtu/models/scaler_rtu_1_2.pkl",
|
14 |
scaler2_path="src/rtu/models/scaler_rtu_3_4.pkl",
|
15 |
)
|
16 |
-
rtu_anomalizer1 = RTUAnomalizer1(
|
17 |
-
prediction_model_path="src/rtu/models/lstm_2rtu_smooth_04.keras",
|
18 |
-
clustering_model_paths=[
|
19 |
-
"src/rtu/models/kmeans_rtu_1.pkl",
|
20 |
-
"src/rtu/models/kmeans_rtu_2.pkl",
|
21 |
-
],
|
22 |
-
pca_model_paths=[
|
23 |
-
"src/rtu/models/pca_rtu_1.pkl",
|
24 |
-
"src/rtu/models/pca_rtu_2.pkl",
|
25 |
-
],
|
26 |
-
num_inputs=rtu_data_pipeline.num_inputs,
|
27 |
-
num_outputs=rtu_data_pipeline.num_outputs,
|
28 |
-
)
|
29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
43 |
)
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
for i in range(
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
|
51 |
# Set the layout of the page to 'wide'
|
@@ -107,10 +154,8 @@ for i in range(4):
|
|
107 |
""",
|
108 |
unsafe_allow_html=True,
|
109 |
)
|
110 |
-
placeholder["sa_temp"].markdown("**SA temp:** -- °
|
111 |
-
placeholder["ra_temp"].markdown("**RA temp:** -- °
|
112 |
-
|
113 |
-
all_data = []
|
114 |
|
115 |
|
116 |
# Temperatures streaming and updates
|
@@ -118,8 +163,8 @@ def update_status_boxes(df):
|
|
118 |
for i in range(4):
|
119 |
sa_temp = df[f"rtu_00{i+1}_sa_temp"].iloc[-1]
|
120 |
ra_temp = df[f"rtu_00{i+1}_ra_temp"].iloc[-1]
|
121 |
-
rtu_placeholders[i]["sa_temp"].markdown(f"**SA temp:** {sa_temp} °
|
122 |
-
rtu_placeholders[i]["ra_temp"].markdown(f"**RA temp:** {ra_temp} °
|
123 |
|
124 |
|
125 |
# Zones
|
@@ -299,7 +344,7 @@ with st.container():
|
|
299 |
distances = []
|
300 |
|
301 |
|
302 |
-
def create_residual_plot(resid_pca_list, rtu_id):
|
303 |
if rtu_id % 2 == 1:
|
304 |
ax1 = 0
|
305 |
ax2 = 1
|
@@ -314,8 +359,8 @@ def create_residual_plot(resid_pca_list, rtu_id):
|
|
314 |
height=500,
|
315 |
)
|
316 |
fig.update_layout(
|
317 |
-
xaxis_range=[-
|
318 |
-
yaxis_range=[-
|
319 |
xaxis=dict(showgrid=True, gridwidth=1, gridcolor="lightgray"),
|
320 |
yaxis=dict(showgrid=True, gridwidth=1, gridcolor="lightgray"),
|
321 |
margin=dict(l=20, r=20, t=20, b=20),
|
@@ -334,17 +379,16 @@ def create_residual_plot(resid_pca_list, rtu_id):
|
|
334 |
|
335 |
resid_placeholder = st.empty()
|
336 |
|
|
|
337 |
|
338 |
while True:
|
339 |
|
340 |
if mqtt_client.data_list:
|
341 |
-
all_data.
|
342 |
-
if len(all_data) >
|
343 |
-
all_data.
|
344 |
-
df = pd.DataFrame(all_data)
|
345 |
|
346 |
-
|
347 |
-
rtu_1_fault = True
|
348 |
|
349 |
df_time = df["date"].iloc[-1] # Obtain the latest datetime of data
|
350 |
|
@@ -360,59 +404,94 @@ while True:
|
|
360 |
update_status_boxes(df)
|
361 |
|
362 |
dist = None
|
363 |
-
|
364 |
-
|
|
|
365 |
|
366 |
df_new1, df_trans1, df_new2, df_trans2 = rtu_data_pipeline.fit(
|
367 |
pd.DataFrame(mqtt_client.data_list)
|
368 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
369 |
if (
|
370 |
not df_new1 is None
|
371 |
and not df_trans1 is None
|
372 |
and not df_new2 is None
|
373 |
and not df_trans2 is None
|
374 |
):
|
375 |
-
|
376 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
377 |
)
|
378 |
(
|
379 |
actual_list_2,
|
380 |
pred_list_2,
|
381 |
resid_list_2,
|
382 |
-
|
383 |
dist_2,
|
384 |
over_threshold_2,
|
385 |
-
) =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
386 |
|
387 |
-
if
|
388 |
-
|
389 |
-
|
390 |
-
resid_pca_list_2 = np.array(resid_pca_list_2)
|
391 |
|
392 |
-
if
|
393 |
with resid_placeholder.container():
|
394 |
resid_rtu1_placeholder, resid_rtu2_placeholder = st.columns(2)
|
395 |
with resid_rtu1_placeholder:
|
396 |
st.subheader("RTU 1 Residuals")
|
397 |
-
fig = create_residual_plot(
|
398 |
st.plotly_chart(fig)
|
399 |
|
400 |
with resid_rtu2_placeholder:
|
401 |
st.subheader("RTU 2 Residuals")
|
402 |
-
fig = create_residual_plot(
|
403 |
st.plotly_chart(fig)
|
404 |
|
405 |
resid_rtu3_placeholder, resid_rtu4_placeholder = st.columns(2)
|
406 |
with resid_rtu3_placeholder:
|
407 |
st.subheader("RTU 3 Residuals")
|
408 |
-
fig = create_residual_plot(
|
409 |
st.plotly_chart(fig)
|
410 |
|
411 |
with resid_rtu4_placeholder:
|
412 |
st.subheader("RTU 4 Residuals")
|
413 |
-
fig = create_residual_plot(
|
414 |
st.plotly_chart(fig)
|
415 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
416 |
# with north_wing_energy_container:
|
417 |
# df_energy = generate_energy_data() # ---- REPLACE WITH ACTUAL DATA ----
|
418 |
# fig, ax = plt.subplots(figsize=(5, 1.5))
|
|
|
1 |
from collections import deque
|
2 |
+
from src.energy_prediction.EnergyPredictionModel import EnergyPredictionModel
|
3 |
+
from src.energy_prediction.EnergyPredictionPipeline import EnergyPredictionPipeline
|
4 |
+
from src.vav.VAVAnomalizer import VAVAnomalizer
|
5 |
+
from src.vav.VAVPipeline import VAVPipeline
|
6 |
import streamlit as st
|
7 |
import pandas as pd
|
8 |
import numpy as np
|
|
|
17 |
scaler1_path="src/rtu/models/scaler_rtu_1_2.pkl",
|
18 |
scaler2_path="src/rtu/models/scaler_rtu_3_4.pkl",
|
19 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
rtu_anomalizers = []
|
22 |
+
|
23 |
+
|
24 |
+
rtu_anomalizers.append(
|
25 |
+
RTUAnomalizer1(
|
26 |
+
prediction_model_path="src/rtu/models/lstm_2rtu_smooth_04.keras",
|
27 |
+
clustering_model_paths=[
|
28 |
+
"src/rtu/models/kmeans_rtu_1.pkl",
|
29 |
+
"src/rtu/models/kmeans_rtu_2.pkl",
|
30 |
+
],
|
31 |
+
pca_model_paths=[
|
32 |
+
"src/rtu/models/pca_rtu_1.pkl",
|
33 |
+
"src/rtu/models/pca_rtu_2.pkl",
|
34 |
+
],
|
35 |
+
num_inputs=rtu_data_pipeline.num_inputs,
|
36 |
+
num_outputs=rtu_data_pipeline.num_outputs,
|
37 |
+
)
|
38 |
+
)
|
39 |
|
40 |
+
rtu_anomalizers.append(
|
41 |
+
RTUAnomalizer1(
|
42 |
+
prediction_model_path="src/rtu/models/lstm_2rtu_smooth_04.keras",
|
43 |
+
clustering_model_paths=[
|
44 |
+
"src/rtu/models/kmeans_rtu_1.pkl",
|
45 |
+
"src/rtu/models/kmeans_rtu_2.pkl",
|
46 |
+
],
|
47 |
+
pca_model_paths=[
|
48 |
+
"src/rtu/models/pca_rtu_1.pkl",
|
49 |
+
"src/rtu/models/pca_rtu_2.pkl",
|
50 |
+
],
|
51 |
+
num_inputs=rtu_data_pipeline.num_inputs,
|
52 |
+
num_outputs=rtu_data_pipeline.num_outputs,
|
53 |
+
)
|
54 |
)
|
55 |
|
56 |
+
vav_pipelines = []
|
57 |
+
vav_anomalizers = []
|
58 |
+
for i in range(1, 2):
|
59 |
+
vav_pipelines.append(
|
60 |
+
VAVPipeline(rtu_id=i, scaler_path=f"src/vav/models/scaler_vav_{i}.pkl")
|
61 |
+
)
|
62 |
+
|
63 |
+
for i in range(1, 2):
|
64 |
+
vav_anomalizers.append(
|
65 |
+
VAVAnomalizer(
|
66 |
+
rtu_id=i,
|
67 |
+
prediction_model_path=f"src/vav/models/lstm_vav_0{i}.keras",
|
68 |
+
clustering_model_path=f"src/vav/models/kmeans_vav_{i}.pkl",
|
69 |
+
pca_model_path=f"src/vav/models/pca_vav_{i}.pkl",
|
70 |
+
num_inputs=vav_pipelines[i - 1].num_inputs,
|
71 |
+
num_outputs=vav_pipelines[i - 1].num_outputs,
|
72 |
+
)
|
73 |
+
)
|
74 |
+
|
75 |
+
|
76 |
+
all_data = pd.read_csv("data/bootstrap_data.csv")
|
77 |
+
|
78 |
+
# energy_pipeline_north = EnergyPredictionPipeline(
|
79 |
+
# scaler_path="src/energy_prediction/models/scalerNorth.pkl",
|
80 |
+
# wing="north",
|
81 |
+
# bootstrap_data=all_data,
|
82 |
+
# )
|
83 |
+
# energy_pipeline_south = EnergyPredictionPipeline(
|
84 |
+
# scaler_path="src/energy_prediction/models/scalerSouth.pkl",
|
85 |
+
# wing="south",
|
86 |
+
# bootstrap_data=all_data,
|
87 |
+
# )
|
88 |
+
|
89 |
+
# energy_prediction_model_north = EnergyPredictionModel(
|
90 |
+
# model_path=r"src/energy_prediction/models/lstm_energy_north_01.keras"
|
91 |
+
# )
|
92 |
+
|
93 |
+
# energy_prediction_model_south = EnergyPredictionModel(
|
94 |
+
# model_path=r"src/energy_prediction/models/lstm_energy_south_01.keras"
|
95 |
+
# )
|
96 |
|
97 |
|
98 |
# Set the layout of the page to 'wide'
|
|
|
154 |
""",
|
155 |
unsafe_allow_html=True,
|
156 |
)
|
157 |
+
placeholder["sa_temp"].markdown("**SA temp:** -- °F")
|
158 |
+
placeholder["ra_temp"].markdown("**RA temp:** -- °F")
|
|
|
|
|
159 |
|
160 |
|
161 |
# Temperatures streaming and updates
|
|
|
163 |
for i in range(4):
|
164 |
sa_temp = df[f"rtu_00{i+1}_sa_temp"].iloc[-1]
|
165 |
ra_temp = df[f"rtu_00{i+1}_ra_temp"].iloc[-1]
|
166 |
+
rtu_placeholders[i]["sa_temp"].markdown(f"**SA temp:** {sa_temp} °F")
|
167 |
+
rtu_placeholders[i]["ra_temp"].markdown(f"**RA temp:** {ra_temp} °F")
|
168 |
|
169 |
|
170 |
# Zones
|
|
|
344 |
distances = []
|
345 |
|
346 |
|
347 |
+
def create_residual_plot(resid_pca_list, rtu_id, lim=8):
|
348 |
if rtu_id % 2 == 1:
|
349 |
ax1 = 0
|
350 |
ax2 = 1
|
|
|
359 |
height=500,
|
360 |
)
|
361 |
fig.update_layout(
|
362 |
+
xaxis_range=[-lim, lim],
|
363 |
+
yaxis_range=[-lim, lim],
|
364 |
xaxis=dict(showgrid=True, gridwidth=1, gridcolor="lightgray"),
|
365 |
yaxis=dict(showgrid=True, gridwidth=1, gridcolor="lightgray"),
|
366 |
margin=dict(l=20, r=20, t=20, b=20),
|
|
|
379 |
|
380 |
resid_placeholder = st.empty()
|
381 |
|
382 |
+
resid_vav_placeholder = st.empty()
|
383 |
|
384 |
while True:
|
385 |
|
386 |
if mqtt_client.data_list:
|
387 |
+
all_data = pd.concat([all_data, pd.DataFrame(mqtt_client.data_list)], axis=0)
|
388 |
+
if len(all_data) > 10080:
|
389 |
+
all_data = all_data.iloc[-10080:]
|
|
|
390 |
|
391 |
+
df = pd.DataFrame(all_data)
|
|
|
392 |
|
393 |
df_time = df["date"].iloc[-1] # Obtain the latest datetime of data
|
394 |
|
|
|
404 |
update_status_boxes(df)
|
405 |
|
406 |
dist = None
|
407 |
+
resid_pca_list_rtu = None
|
408 |
+
resid_pca_list_rtu_2 = None
|
409 |
+
resid_pca_list_vav_1 = None
|
410 |
|
411 |
df_new1, df_trans1, df_new2, df_trans2 = rtu_data_pipeline.fit(
|
412 |
pd.DataFrame(mqtt_client.data_list)
|
413 |
)
|
414 |
+
|
415 |
+
vav_1_df_new, vav_1_df_trans = vav_pipelines[0].fit(
|
416 |
+
pd.DataFrame(mqtt_client.data_list)
|
417 |
+
)
|
418 |
+
vav_anomalizers[0].num_inputs = vav_pipelines[0].num_inputs
|
419 |
+
vav_anomalizers[0].num_outputs = vav_pipelines[0].num_outputs
|
420 |
+
|
421 |
if (
|
422 |
not df_new1 is None
|
423 |
and not df_trans1 is None
|
424 |
and not df_new2 is None
|
425 |
and not df_trans2 is None
|
426 |
):
|
427 |
+
(
|
428 |
+
actual_list,
|
429 |
+
pred_list,
|
430 |
+
resid_list,
|
431 |
+
resid_pca_list_rtu,
|
432 |
+
dist,
|
433 |
+
over_threshold,
|
434 |
+
) = rtu_anomalizers[0].pipeline(
|
435 |
+
df_new1, df_trans1, rtu_data_pipeline.scaler1
|
436 |
)
|
437 |
(
|
438 |
actual_list_2,
|
439 |
pred_list_2,
|
440 |
resid_list_2,
|
441 |
+
resid_pca_list_rtu_2,
|
442 |
dist_2,
|
443 |
over_threshold_2,
|
444 |
+
) = rtu_anomalizers[1].pipeline(
|
445 |
+
df_new1, df_trans1, rtu_data_pipeline.scaler1
|
446 |
+
)
|
447 |
+
if not vav_1_df_new is None:
|
448 |
+
(
|
449 |
+
actual_list_vav_1,
|
450 |
+
pred_list_vav_1,
|
451 |
+
resid_list_vav_1,
|
452 |
+
resid_pca_list_vav_1,
|
453 |
+
dist_vav_1,
|
454 |
+
) = vav_anomalizers[0].pipeline(
|
455 |
+
vav_1_df_new, vav_1_df_trans, vav_pipelines[0].scaler
|
456 |
+
)
|
457 |
|
458 |
+
if resid_pca_list_rtu is not None:
|
459 |
+
resid_pca_list_rtu = np.array(resid_pca_list_rtu)
|
460 |
+
resid_pca_list_rtu_2 = np.array(resid_pca_list_rtu_2)
|
|
|
461 |
|
462 |
+
if resid_pca_list_rtu is not None:
|
463 |
with resid_placeholder.container():
|
464 |
resid_rtu1_placeholder, resid_rtu2_placeholder = st.columns(2)
|
465 |
with resid_rtu1_placeholder:
|
466 |
st.subheader("RTU 1 Residuals")
|
467 |
+
fig = create_residual_plot(resid_pca_list_rtu, rtu_id=1)
|
468 |
st.plotly_chart(fig)
|
469 |
|
470 |
with resid_rtu2_placeholder:
|
471 |
st.subheader("RTU 2 Residuals")
|
472 |
+
fig = create_residual_plot(resid_pca_list_rtu, rtu_id=2)
|
473 |
st.plotly_chart(fig)
|
474 |
|
475 |
resid_rtu3_placeholder, resid_rtu4_placeholder = st.columns(2)
|
476 |
with resid_rtu3_placeholder:
|
477 |
st.subheader("RTU 3 Residuals")
|
478 |
+
fig = create_residual_plot(resid_pca_list_rtu, rtu_id=3)
|
479 |
st.plotly_chart(fig)
|
480 |
|
481 |
with resid_rtu4_placeholder:
|
482 |
st.subheader("RTU 4 Residuals")
|
483 |
+
fig = create_residual_plot(resid_pca_list_rtu, rtu_id=4)
|
484 |
st.plotly_chart(fig)
|
485 |
|
486 |
+
if resid_pca_list_vav_1 is not None:
|
487 |
+
print(resid_pca_list_vav_1)
|
488 |
+
with resid_vav_placeholder.container():
|
489 |
+
st.subheader("VAV 1 Residuals")
|
490 |
+
fig = create_residual_plot(
|
491 |
+
np.array(resid_pca_list_vav_1), rtu_id=1, lim=15
|
492 |
+
)
|
493 |
+
st.plotly_chart(fig)
|
494 |
+
|
495 |
# with north_wing_energy_container:
|
496 |
# df_energy = generate_energy_data() # ---- REPLACE WITH ACTUAL DATA ----
|
497 |
# fig, ax = plt.subplots(figsize=(5, 1.5))
|
mqttpublisher.ipynb
CHANGED
The diff for this file is too large to render.
See raw diff
|
|
physLSTM/kmeans_vav_2.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:eac01ceecdae11713ee21462a8bd3dc7ea32e740c3daa42795b266a05e7c424a
|
3 |
+
size 1567961
|
physLSTM/lstm_vav_rtu1.ipynb
CHANGED
@@ -334,7 +334,7 @@
|
|
334 |
"\n",
|
335 |
"checkpoint_path = \"lstm_vav_01.keras\"\n",
|
336 |
"checkpoint_callback = ModelCheckpoint(filepath=checkpoint_path, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n",
|
337 |
-
"model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=128, verbose=1, callbacks=[checkpoint_callback])"
|
338 |
]
|
339 |
},
|
340 |
{
|
@@ -450,26 +450,45 @@
|
|
450 |
"idx_to_col"
|
451 |
]
|
452 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
453 |
{
|
454 |
"cell_type": "code",
|
455 |
"execution_count": 84,
|
456 |
"metadata": {},
|
457 |
"outputs": [],
|
458 |
"source": [
|
459 |
-
"%matplotlib
|
460 |
-
"
|
461 |
-
"
|
462 |
-
"
|
463 |
-
"
|
464 |
-
"
|
465 |
-
"
|
466 |
-
"\n",
|
467 |
-
"\n",
|
468 |
-
"
|
469 |
-
"
|
470 |
-
"
|
471 |
-
"
|
472 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
473 |
]
|
474 |
},
|
475 |
{
|
@@ -538,30 +557,32 @@
|
|
538 |
"\n",
|
539 |
"k = 2\n",
|
540 |
"\n",
|
|
|
|
|
|
|
541 |
"kmeans = KMeans(n_clusters=k)\n",
|
542 |
"\n",
|
543 |
"kmeans.fit(X)\n",
|
544 |
"\n",
|
545 |
"\n",
|
546 |
-
"pca = PCA(n_components=2)\n",
|
547 |
-
"X = pca.fit_transform(X)\n",
|
548 |
-
"\n",
|
549 |
-
"\n",
|
550 |
"\n",
|
551 |
"# Getting the cluster centers and labels\n",
|
552 |
"centroids = kmeans.cluster_centers_\n",
|
553 |
-
"centroids = pca.transform(centroids)\n",
|
554 |
"labels = kmeans.labels_\n",
|
555 |
"\n",
|
556 |
"# Plotting the data points and cluster centers\n",
|
557 |
"plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', alpha=0.5)\n",
|
558 |
"plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', c='red', s=200, linewidths=2)\n",
|
|
|
|
|
559 |
"plt.title('KMeans Clustering')\n",
|
560 |
"plt.xlabel('Feature 1')\n",
|
561 |
"plt.ylabel('Feature 2')\n",
|
562 |
-
"plt.
|
563 |
"\n",
|
564 |
-
"joblib.dump(kmeans, '
|
|
|
565 |
]
|
566 |
},
|
567 |
{
|
|
|
334 |
"\n",
|
335 |
"checkpoint_path = \"lstm_vav_01.keras\"\n",
|
336 |
"checkpoint_callback = ModelCheckpoint(filepath=checkpoint_path, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n",
|
337 |
+
"# model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=128, verbose=1, callbacks=[checkpoint_callback])"
|
338 |
]
|
339 |
},
|
340 |
{
|
|
|
450 |
"idx_to_col"
|
451 |
]
|
452 |
},
|
453 |
+
{
|
454 |
+
"cell_type": "code",
|
455 |
+
"execution_count": null,
|
456 |
+
"metadata": {},
|
457 |
+
"outputs": [],
|
458 |
+
"source": [
|
459 |
+
"test_predict1_unscaled = test_predict1*scaler.scale_[0:31] + scaler.mean_[0:31]\n",
|
460 |
+
"y_test_unscaled = y_test*scaler.scale_[0:31] + scaler.mean_[0:31]"
|
461 |
+
]
|
462 |
+
},
|
463 |
{
|
464 |
"cell_type": "code",
|
465 |
"execution_count": 84,
|
466 |
"metadata": {},
|
467 |
"outputs": [],
|
468 |
"source": [
|
469 |
+
"%matplotlib inline\n",
|
470 |
+
"var = 0\n",
|
471 |
+
"\n",
|
472 |
+
"df = pd.DataFrame([testdataset_df.index[31:],test_predict1_unscaled[:,var], y_test_unscaled[:,var]] ).T\n",
|
473 |
+
"fig, ax = plt.subplots(figsize=(10,8))\n",
|
474 |
+
"df.plot(x = 0, y=1, ax = ax, label = 'Predicted')\n",
|
475 |
+
"df.plot(x = 0, y=2, ax = ax, label = 'Actual')\n",
|
476 |
+
"\n",
|
477 |
+
"anomalies = df.where(df[1]-df[2]>0.38)[0]\n",
|
478 |
+
"df['anomalies'] = anomalies\n",
|
479 |
+
"\n",
|
480 |
+
"df_new = df.dropna()\n",
|
481 |
+
"\n",
|
482 |
+
"df_new.plot.scatter(x='anomalies', y=1, c='r', ax = ax, label = 'Anomalies')\n",
|
483 |
+
"\n",
|
484 |
+
"# ax.scatter(anomalies,test_predict1[anomalies,var], color='black',marker =\"o\",s=100 )\n",
|
485 |
+
"\n",
|
486 |
+
"\n",
|
487 |
+
"ax.set_title('Testing Data - Predicted vs Actual [Zone 72 Temperature]', fontsize=20)\n",
|
488 |
+
"ax.set_xlabel('Time', fontsize=15)\n",
|
489 |
+
"ax.set_ylabel('Value', fontsize = 15)\n",
|
490 |
+
"ax.legend(fontsize = 15)\n",
|
491 |
+
"fig.tight_layout()"
|
492 |
]
|
493 |
},
|
494 |
{
|
|
|
557 |
"\n",
|
558 |
"k = 2\n",
|
559 |
"\n",
|
560 |
+
"pca = PCA(n_components=2)\n",
|
561 |
+
"X = pca.fit_transform(X)\n",
|
562 |
+
"\n",
|
563 |
"kmeans = KMeans(n_clusters=k)\n",
|
564 |
"\n",
|
565 |
"kmeans.fit(X)\n",
|
566 |
"\n",
|
567 |
"\n",
|
|
|
|
|
|
|
|
|
568 |
"\n",
|
569 |
"# Getting the cluster centers and labels\n",
|
570 |
"centroids = kmeans.cluster_centers_\n",
|
571 |
+
"# centroids = pca.transform(centroids)\n",
|
572 |
"labels = kmeans.labels_\n",
|
573 |
"\n",
|
574 |
"# Plotting the data points and cluster centers\n",
|
575 |
"plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', alpha=0.5)\n",
|
576 |
"plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', c='red', s=200, linewidths=2)\n",
|
577 |
+
"plt.text(centroids[0,0]+0.2, centroids[0,1]+0.5, 'Normal', fontsize=12, color='red')\n",
|
578 |
+
"plt.text(centroids[1,0]+0.5, centroids[1,1]+0.2, 'Anomaly', fontsize=12, color='red')\n",
|
579 |
"plt.title('KMeans Clustering')\n",
|
580 |
"plt.xlabel('Feature 1')\n",
|
581 |
"plt.ylabel('Feature 2')\n",
|
582 |
+
"plt.tight_layout()\n",
|
583 |
"\n",
|
584 |
+
"joblib.dump(kmeans, 'kmeans_vav_2.pkl')\n",
|
585 |
+
"joblib.dump(pca, 'pca_vav_2.pkl')"
|
586 |
]
|
587 |
},
|
588 |
{
|
physLSTM/lstm_vav_rtu2.ipynb
CHANGED
The diff for this file is too large to render.
See raw diff
|
|
physLSTM/pca_vav_2.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:00484ce0c76fc9df1f8f119325a12ec7be5baf8879d4ac192448b2d7ba397c7e
|
3 |
+
size 1323
|
physLSTM/scaler_vav_1.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:293ee3c9082e7104dfc96425cecad2a44e5914bbd1f43c25a0fd8c36507b103a
|
3 |
+
size 1925
|
src/energy_prediction/{EnergyPredictionNorth.py → EnergyPredictionModel.py}
RENAMED
@@ -2,13 +2,13 @@ import numpy as np
|
|
2 |
import pandas as pd
|
3 |
from tensorflow.keras.models import load_model
|
4 |
|
5 |
-
|
|
|
6 |
"""
|
7 |
Class for predicting energy consumption in the north wing of the building.
|
8 |
"""
|
9 |
|
10 |
-
def __init__(self,
|
11 |
-
model_path=None):
|
12 |
"""
|
13 |
Initialize the EnergyPredictionNorth object.
|
14 |
|
@@ -38,15 +38,14 @@ class EnergyPredictionNorth:
|
|
38 |
np.ndarray: Predicted energy consumption values.
|
39 |
"""
|
40 |
return self.model.predict(data, verbose=0)
|
41 |
-
|
42 |
-
def inverse_transform(self, scaler, pred
|
43 |
"""
|
44 |
Inverse transform the predicted and actual values.
|
45 |
|
46 |
Args:
|
47 |
scaler (object): Scaler object for inverse transformation.
|
48 |
pred (array): Predicted values.
|
49 |
-
df_trans (DataFrame): Transformed input data.
|
50 |
|
51 |
Returns:
|
52 |
tuple: A tuple containing the actual and predicted values after inverse transformation.
|
@@ -54,6 +53,23 @@ class EnergyPredictionNorth:
|
|
54 |
mean = scaler.mean_[0]
|
55 |
std = scaler.scale_[0]
|
56 |
|
57 |
-
pred
|
58 |
-
actual = df_trans[:,0] * std + mean
|
59 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import pandas as pd
|
3 |
from tensorflow.keras.models import load_model
|
4 |
|
5 |
+
|
6 |
+
class EnergyPredictionModel:
|
7 |
"""
|
8 |
Class for predicting energy consumption in the north wing of the building.
|
9 |
"""
|
10 |
|
11 |
+
def __init__(self, model_path=None):
|
|
|
12 |
"""
|
13 |
Initialize the EnergyPredictionNorth object.
|
14 |
|
|
|
38 |
np.ndarray: Predicted energy consumption values.
|
39 |
"""
|
40 |
return self.model.predict(data, verbose=0)
|
41 |
+
|
42 |
+
def inverse_transform(self, scaler, pred):
|
43 |
"""
|
44 |
Inverse transform the predicted and actual values.
|
45 |
|
46 |
Args:
|
47 |
scaler (object): Scaler object for inverse transformation.
|
48 |
pred (array): Predicted values.
|
|
|
49 |
|
50 |
Returns:
|
51 |
tuple: A tuple containing the actual and predicted values after inverse transformation.
|
|
|
53 |
mean = scaler.mean_[0]
|
54 |
std = scaler.scale_[0]
|
55 |
|
56 |
+
pred = pred * std + mean
|
57 |
+
# actual = df_trans[:,0] * std + mean
|
58 |
+
return pred
|
59 |
+
|
60 |
+
def pipeline(self, data, scaler):
|
61 |
+
"""
|
62 |
+
Run the prediction pipeline.
|
63 |
+
|
64 |
+
Args:
|
65 |
+
df (pd.DataFrame): Input data for prediction.
|
66 |
+
scaler (object): Scaler object for inverse transformation.
|
67 |
+
|
68 |
+
Returns:
|
69 |
+
tuple: A tuple containing the actual and predicted values after inverse transformation.
|
70 |
+
"""
|
71 |
+
|
72 |
+
pred = self.predict(data)
|
73 |
+
pred_scaled = self.inverse_transform(scaler, pred)
|
74 |
+
|
75 |
+
return pred_scaled
|
src/energy_prediction/EnergyPredictionPipeline.py
CHANGED
@@ -6,78 +6,89 @@ import joblib
|
|
6 |
import json
|
7 |
import numpy as np
|
8 |
|
|
|
9 |
class EnergyPredictionPipeline:
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
"
|
23 |
-
|
24 |
-
|
|
|
25 |
def get_scaler(self, scaler_path):
|
26 |
return joblib.load(scaler_path)
|
27 |
-
|
28 |
def transform_windows(self, df):
|
29 |
-
return self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
-
|
|
|
|
|
32 |
|
33 |
-
df[
|
34 |
-
df[
|
35 |
-
df[
|
36 |
|
37 |
-
df
|
38 |
-
df['hour_encoding'] = np.sin(2*np.pi*df['hour_of_day']/24)
|
39 |
-
df['month_encoding'] = np.sin(2*np.pi*df['month']/12)
|
40 |
|
41 |
return df
|
42 |
-
|
43 |
-
def prepare_input(self,
|
44 |
-
|
45 |
-
df =
|
46 |
df["date"] = pd.to_datetime(df["date"])
|
47 |
df.set_index("date", inplace=True)
|
48 |
-
df = df.resample("
|
49 |
-
|
50 |
df = self.date_encoder(df)
|
51 |
-
|
52 |
df.reset_index(inplace=True, drop=True)
|
|
|
|
|
53 |
|
54 |
return df
|
55 |
-
|
56 |
-
def extract_data_from_message(self, message):
|
57 |
-
payload = json.loads(message.payload.decode())
|
58 |
|
59 |
-
|
|
|
|
|
60 |
|
61 |
-
k = {}
|
62 |
-
for col in self.input_col_names:
|
63 |
-
k[col] = payload[col]
|
64 |
-
self.df.loc[len_df] = k
|
65 |
return self.df
|
66 |
-
|
67 |
def get_window(self, df):
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
|
|
|
|
72 |
else:
|
73 |
return None
|
74 |
-
|
75 |
def fit(self, message):
|
76 |
-
df_new
|
77 |
-
df_window
|
78 |
if df_window is not None:
|
79 |
df = self.prepare_input(df_window)
|
80 |
df = self.transform_windows(df)
|
|
|
|
|
|
|
81 |
else:
|
82 |
df = None
|
83 |
-
|
|
|
|
6 |
import json
|
7 |
import numpy as np
|
8 |
|
9 |
+
|
10 |
class EnergyPredictionPipeline:
|
11 |
+
scaler = None
|
12 |
+
|
13 |
+
def __init__(
|
14 |
+
self, scaler_path=None, wing="north", bootstrap_data: pd.DataFrame = None
|
15 |
+
):
|
16 |
+
|
17 |
+
if scaler_path:
|
18 |
+
self.scaler = self.get_scaler(scaler_path)
|
19 |
+
|
20 |
+
if wing == "north":
|
21 |
+
self.input_col_names = ["date", "hvac_N"]
|
22 |
+
elif wing == "south":
|
23 |
+
self.input_col_names = ["date", "hvac_S"]
|
24 |
+
|
25 |
+
self.df = bootstrap_data[self.input_col_names]
|
26 |
+
|
27 |
def get_scaler(self, scaler_path):
|
28 |
return joblib.load(scaler_path)
|
29 |
+
|
30 |
def transform_windows(self, df):
|
31 |
+
return self.scaler.transform(df)
|
32 |
+
|
33 |
+
def add_dimension(self, df):
|
34 |
+
return df.reshape((1, df.shape[0], df.shape[1]))
|
35 |
+
|
36 |
+
def convert_nan(self, df):
|
37 |
+
return np.nan_to_num(df)
|
38 |
+
|
39 |
+
def date_encoder(self, df):
|
40 |
|
41 |
+
df["day_of_week"] = df.index.dayofweek
|
42 |
+
df["hour_of_day"] = df.index.hour
|
43 |
+
df["month"] = df.index.month
|
44 |
|
45 |
+
df["day_encoding"] = np.sin(2 * np.pi * df["day_of_week"] / 7)
|
46 |
+
df["hour_encoding"] = np.sin(2 * np.pi * df["hour_of_day"] / 24)
|
47 |
+
df["month_encoding"] = np.sin(2 * np.pi * df["month"] / 12)
|
48 |
|
49 |
+
df.drop(columns=["day_of_week", "hour_of_day", "month"], inplace=True)
|
|
|
|
|
50 |
|
51 |
return df
|
52 |
+
|
53 |
+
def prepare_input(self, df1):
|
54 |
+
|
55 |
+
df = df1.copy()
|
56 |
df["date"] = pd.to_datetime(df["date"])
|
57 |
df.set_index("date", inplace=True)
|
58 |
+
df = df.resample("60T").mean()
|
|
|
59 |
df = self.date_encoder(df)
|
|
|
60 |
df.reset_index(inplace=True, drop=True)
|
61 |
+
df = df.astype("float32")
|
62 |
+
df = df.iloc[-24 * 7 :]
|
63 |
|
64 |
return df
|
|
|
|
|
|
|
65 |
|
66 |
+
def extract_data_from_message(self, df):
|
67 |
+
df = df[self.input_col_names]
|
68 |
+
self.df = pd.concat([self.df, df], axis=0)
|
69 |
|
|
|
|
|
|
|
|
|
70 |
return self.df
|
71 |
+
|
72 |
def get_window(self, df):
|
73 |
+
|
74 |
+
time = df["date"].iloc[-1]
|
75 |
+
time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
|
76 |
+
|
77 |
+
if time.minute == 0 & time.second == 0:
|
78 |
+
return df
|
79 |
else:
|
80 |
return None
|
81 |
+
|
82 |
def fit(self, message):
|
83 |
+
df_new = self.extract_data_from_message(message)
|
84 |
+
df_window = self.get_window(df_new)
|
85 |
if df_window is not None:
|
86 |
df = self.prepare_input(df_window)
|
87 |
df = self.transform_windows(df)
|
88 |
+
df = self.convert_nan(df)
|
89 |
+
df = self.add_dimension(df)
|
90 |
+
|
91 |
else:
|
92 |
df = None
|
93 |
+
|
94 |
+
return df
|
src/energy_prediction/EnergyPredictionSouth.py
DELETED
File without changes
|
src/energy_prediction/models/lstm_energy_south_01.keras
ADDED
Binary file (430 kB). View file
|
|
src/energy_prediction/models/scalerSouth.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:28b4ee66e0160ad1c033e33728ea5b349a168c9070fa6e813184c63dd7ba3e52
|
3 |
+
size 689
|
src/energy_prediction/test_main.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from energy_prediction.EnergyPredictionModel import EnergyPredictionModel
|
2 |
+
from energy_prediction.EnergyPredictionPipeline import EnergyPredictionPipeline
|
3 |
+
import paho.mqtt.client as mqtt
|
4 |
+
import json
|
5 |
+
|
6 |
+
broker_address = "localhost"
|
7 |
+
broker_port = 1883
|
8 |
+
topic = "sensor_data"
|
9 |
+
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
10 |
+
|
11 |
+
def main():
|
12 |
+
prediction_data_pipeline_north = EnergyPredictionPipeline(scaler_path="src\energy_prediction\models\scalerNorth.pkl", wing='north')
|
13 |
+
prediction_data_pipeline_south = EnergyPredictionPipeline(scaler_path="src\energy_prediction\models\scalerSouth.pkl", wing='south')
|
14 |
+
|
15 |
+
# Energy Prediction North wing
|
16 |
+
energy_prediction_north = EnergyPredictionModel(
|
17 |
+
model_path="src/energy_prediction/models/lstm_energy_north_01.keras"
|
18 |
+
)
|
19 |
+
# Energy Prediction South wing
|
20 |
+
energy_prediction_south = EnergyPredictionModel(
|
21 |
+
model_path="src/energy_prediction/models/lstm_energy_south_01.keras"
|
22 |
+
)
|
23 |
+
|
24 |
+
def on_message(client, userdata, message):
|
25 |
+
dfN = prediction_data_pipeline_north.fit(message)
|
26 |
+
dfS = prediction_data_pipeline_south.fit(message)
|
27 |
+
|
28 |
+
if not(dfN is None and dfS is None):
|
29 |
+
outN = energy_prediction_north.pipeline(dfN, prediction_data_pipeline_north.scaler)
|
30 |
+
outS = energy_prediction_south.pipeline(dfS, prediction_data_pipeline_south.scaler)
|
31 |
+
return outN, outS
|
32 |
+
else:
|
33 |
+
return None
|
34 |
+
|
35 |
+
print("Connecting to broker")
|
36 |
+
client.on_message = on_message
|
37 |
+
client.connect(broker_address, broker_port)
|
38 |
+
client.subscribe(topic)
|
39 |
+
client.loop_forever()
|
40 |
+
|
41 |
+
if __name__ == "__main__":
|
42 |
+
main()
|
43 |
+
|
src/vav/VAVAnomalizer.py
CHANGED
@@ -1,4 +1,6 @@
|
|
1 |
import numpy as np
|
|
|
|
|
2 |
from tensorflow.keras.models import load_model
|
3 |
import joblib
|
4 |
|
@@ -9,6 +11,7 @@ class VAVAnomalizer:
|
|
9 |
rtu_id,
|
10 |
prediction_model_path,
|
11 |
clustering_model_path,
|
|
|
12 |
num_inputs,
|
13 |
num_outputs,
|
14 |
):
|
@@ -18,6 +21,7 @@ class VAVAnomalizer:
|
|
18 |
Args:
|
19 |
rtu_id (int): The ID of the RTU (Roof Top Unit) associated with the VAV (Variable Air Volume) system.
|
20 |
prediction_model_path (str): The file path to the prediction model.
|
|
|
21 |
clustering_model_path (str): The file path to the clustering model.
|
22 |
num_inputs (int): The number of input features for the prediction model.
|
23 |
num_outputs (int): The number of output features for the prediction model.
|
@@ -25,18 +29,23 @@ class VAVAnomalizer:
|
|
25 |
self.rtu_id = rtu_id
|
26 |
self.num_inputs = num_inputs
|
27 |
self.num_outputs = num_outputs
|
28 |
-
self.load_models(prediction_model_path, clustering_model_path)
|
|
|
|
|
|
|
29 |
|
30 |
-
def load_models(self, prediction_model_path, clustering_model_path):
|
31 |
"""
|
32 |
Loads the prediction model and clustering model.
|
33 |
|
34 |
Args:
|
35 |
prediction_model_path (str): The file path to the prediction model.
|
|
|
36 |
clustering_model_path (str): The file path to the clustering model.
|
37 |
"""
|
38 |
self.model = load_model(prediction_model_path)
|
39 |
-
self.
|
|
|
40 |
|
41 |
def initialize_lists(self, size=30):
|
42 |
"""
|
@@ -48,8 +57,14 @@ class VAVAnomalizer:
|
|
48 |
Returns:
|
49 |
tuple: A tuple containing three lists initialized with zeros.
|
50 |
"""
|
51 |
-
initial_values = [0] * size
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
def predict(self, df_new):
|
55 |
"""
|
@@ -76,7 +91,7 @@ class VAVAnomalizer:
|
|
76 |
numpy.ndarray: The residuals.
|
77 |
"""
|
78 |
actual = df_trans[30, : self.num_outputs]
|
79 |
-
resid =
|
80 |
return actual, resid
|
81 |
|
82 |
def calculate_distances(self, resid):
|
@@ -90,10 +105,27 @@ class VAVAnomalizer:
|
|
90 |
array: Array of distances.
|
91 |
"""
|
92 |
dist = []
|
93 |
-
dist.append(
|
|
|
|
|
|
|
|
|
|
|
94 |
|
95 |
return np.array(dist)
|
96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
def resize_prediction(self, pred, df_trans):
|
98 |
"""
|
99 |
Resize the predicted values to match the shape of the transformed input data.
|
@@ -129,7 +161,7 @@ class VAVAnomalizer:
|
|
129 |
actual = scaler.inverse_transform(np.array([df_trans[30, :]]))
|
130 |
return actual, pred
|
131 |
|
132 |
-
def update_lists(self,
|
133 |
"""
|
134 |
Update the lists of actual, predicted, and residual values.
|
135 |
|
@@ -137,6 +169,7 @@ class VAVAnomalizer:
|
|
137 |
actual_list (list): List of actual values.
|
138 |
pred_list (list): List of predicted values.
|
139 |
resid_list (list): List of residual values.
|
|
|
140 |
actual (array): Actual values.
|
141 |
pred (array): Predicted values.
|
142 |
resid (array): Residual values.
|
@@ -144,13 +177,15 @@ class VAVAnomalizer:
|
|
144 |
Returns:
|
145 |
tuple: A tuple containing the updated lists of actual, predicted, and residual values.
|
146 |
"""
|
147 |
-
actual_list.pop(0)
|
148 |
-
pred_list.pop(0)
|
149 |
-
resid_list.pop(0)
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
|
|
|
|
154 |
|
155 |
def pipeline(self, df_new, df_trans, scaler):
|
156 |
"""
|
@@ -164,13 +199,13 @@ class VAVAnomalizer:
|
|
164 |
Returns:
|
165 |
tuple: A tuple containing the lists of actual, predicted, and residual values, and the distances.
|
166 |
"""
|
167 |
-
actual_list, pred_list, resid_list = self.initialize_lists()
|
168 |
pred = self.predict(df_new)
|
169 |
actual, resid = self.calculate_residuals(df_trans, pred)
|
170 |
pred = self.resize_prediction(pred, df_trans)
|
171 |
actual, pred = self.inverse_transform(scaler, pred, df_trans)
|
172 |
-
|
173 |
-
|
|
|
174 |
)
|
175 |
dist = self.calculate_distances(resid)
|
176 |
-
return actual_list, pred_list, resid_list, dist
|
|
|
1 |
import numpy as np
|
2 |
+
from sklearn.cluster import KMeans
|
3 |
+
from sklearn.decomposition import PCA
|
4 |
from tensorflow.keras.models import load_model
|
5 |
import joblib
|
6 |
|
|
|
11 |
rtu_id,
|
12 |
prediction_model_path,
|
13 |
clustering_model_path,
|
14 |
+
pca_model_path,
|
15 |
num_inputs,
|
16 |
num_outputs,
|
17 |
):
|
|
|
21 |
Args:
|
22 |
rtu_id (int): The ID of the RTU (Roof Top Unit) associated with the VAV (Variable Air Volume) system.
|
23 |
prediction_model_path (str): The file path to the prediction model.
|
24 |
+
pca_model_path (str): The file path to the PCA model.
|
25 |
clustering_model_path (str): The file path to the clustering model.
|
26 |
num_inputs (int): The number of input features for the prediction model.
|
27 |
num_outputs (int): The number of output features for the prediction model.
|
|
|
29 |
self.rtu_id = rtu_id
|
30 |
self.num_inputs = num_inputs
|
31 |
self.num_outputs = num_outputs
|
32 |
+
self.load_models(prediction_model_path, clustering_model_path, pca_model_path)
|
33 |
+
self.actual_list, self.pred_list, self.resid_list, self.resid_pca_list = (
|
34 |
+
self.initialize_lists()
|
35 |
+
)
|
36 |
|
37 |
+
def load_models(self, prediction_model_path, clustering_model_path, pca_model_path):
|
38 |
"""
|
39 |
Loads the prediction model and clustering model.
|
40 |
|
41 |
Args:
|
42 |
prediction_model_path (str): The file path to the prediction model.
|
43 |
+
pca_model_path (str): The file path to the PCA model.
|
44 |
clustering_model_path (str): The file path to the clustering model.
|
45 |
"""
|
46 |
self.model = load_model(prediction_model_path)
|
47 |
+
self.pca_model: PCA = joblib.load(pca_model_path)
|
48 |
+
self.kmeans_model: KMeans = joblib.load(clustering_model_path)
|
49 |
|
50 |
def initialize_lists(self, size=30):
|
51 |
"""
|
|
|
57 |
Returns:
|
58 |
tuple: A tuple containing three lists initialized with zeros.
|
59 |
"""
|
60 |
+
initial_values = [[0] * self.num_outputs] * size
|
61 |
+
initial_values1 = [[0] * 2] * size
|
62 |
+
return (
|
63 |
+
initial_values.copy(),
|
64 |
+
initial_values.copy(),
|
65 |
+
initial_values.copy(),
|
66 |
+
initial_values1.copy(),
|
67 |
+
)
|
68 |
|
69 |
def predict(self, df_new):
|
70 |
"""
|
|
|
91 |
numpy.ndarray: The residuals.
|
92 |
"""
|
93 |
actual = df_trans[30, : self.num_outputs]
|
94 |
+
resid = pred - actual
|
95 |
return actual, resid
|
96 |
|
97 |
def calculate_distances(self, resid):
|
|
|
105 |
array: Array of distances.
|
106 |
"""
|
107 |
dist = []
|
108 |
+
dist.append(
|
109 |
+
np.linalg.norm(
|
110 |
+
self.pca_model.transform(resid.reshape(1, -1))
|
111 |
+
- self.kmeans_model.cluster_centers_[0]
|
112 |
+
)
|
113 |
+
)
|
114 |
|
115 |
return np.array(dist)
|
116 |
|
117 |
+
def residual_pca(self, resid):
|
118 |
+
"""
|
119 |
+
Perform PCA on the residuals.
|
120 |
+
|
121 |
+
Args:
|
122 |
+
resid (array): Residual values.
|
123 |
+
|
124 |
+
Returns:
|
125 |
+
array: Transformed residuals.
|
126 |
+
"""
|
127 |
+
return self.pca_model.transform(resid.reshape(1, -1))
|
128 |
+
|
129 |
def resize_prediction(self, pred, df_trans):
|
130 |
"""
|
131 |
Resize the predicted values to match the shape of the transformed input data.
|
|
|
161 |
actual = scaler.inverse_transform(np.array([df_trans[30, :]]))
|
162 |
return actual, pred
|
163 |
|
164 |
+
def update_lists(self, actual, pred, resid, resid_pca):
|
165 |
"""
|
166 |
Update the lists of actual, predicted, and residual values.
|
167 |
|
|
|
169 |
actual_list (list): List of actual values.
|
170 |
pred_list (list): List of predicted values.
|
171 |
resid_list (list): List of residual values.
|
172 |
+
resid_pca_list (list): List of PCA-transformed residual values.
|
173 |
actual (array): Actual values.
|
174 |
pred (array): Predicted values.
|
175 |
resid (array): Residual values.
|
|
|
177 |
Returns:
|
178 |
tuple: A tuple containing the updated lists of actual, predicted, and residual values.
|
179 |
"""
|
180 |
+
self.actual_list.pop(0)
|
181 |
+
self.pred_list.pop(0)
|
182 |
+
self.resid_list.pop(0)
|
183 |
+
self.resid_pca_list.pop(0)
|
184 |
+
self.actual_list.append(actual.flatten().tolist())
|
185 |
+
self.pred_list.append(pred.flatten().tolist())
|
186 |
+
self.resid_list.append(resid.flatten().tolist())
|
187 |
+
self.resid_pca_list.append(resid_pca.flatten().tolist())
|
188 |
+
return self.actual_list, self.pred_list, self.resid_list, self.resid_pca_list
|
189 |
|
190 |
def pipeline(self, df_new, df_trans, scaler):
|
191 |
"""
|
|
|
199 |
Returns:
|
200 |
tuple: A tuple containing the lists of actual, predicted, and residual values, and the distances.
|
201 |
"""
|
|
|
202 |
pred = self.predict(df_new)
|
203 |
actual, resid = self.calculate_residuals(df_trans, pred)
|
204 |
pred = self.resize_prediction(pred, df_trans)
|
205 |
actual, pred = self.inverse_transform(scaler, pred, df_trans)
|
206 |
+
resid_pca = self.residual_pca(resid)
|
207 |
+
actual_list, pred_list, resid_list, resid_pca_list = self.update_lists(
|
208 |
+
actual, pred, resid, resid_pca
|
209 |
)
|
210 |
dist = self.calculate_distances(resid)
|
211 |
+
return actual_list, pred_list, resid_list, resid_pca_list, dist
|
src/vav/VAVPipeline.py
CHANGED
@@ -39,28 +39,7 @@ class VAVPipeline:
|
|
39 |
if rtu_id == 1:
|
40 |
self.zones = [69, 68, 67, 66, 65, 64, 42, 41, 40, 39, 38, 37, 36]
|
41 |
if rtu_id == 2:
|
42 |
-
self.zones = [
|
43 |
-
72,
|
44 |
-
71,
|
45 |
-
63,
|
46 |
-
62,
|
47 |
-
60,
|
48 |
-
59,
|
49 |
-
58,
|
50 |
-
57,
|
51 |
-
50,
|
52 |
-
49,
|
53 |
-
44,
|
54 |
-
43,
|
55 |
-
35,
|
56 |
-
34,
|
57 |
-
33,
|
58 |
-
32,
|
59 |
-
31,
|
60 |
-
30,
|
61 |
-
29,
|
62 |
-
28,
|
63 |
-
]
|
64 |
|
65 |
self.output_col_names = []
|
66 |
self.input_col_names = [
|
@@ -171,7 +150,7 @@ class VAVPipeline:
|
|
171 |
self.num_outputs = len(self.output_col_names)
|
172 |
self.df = pd.DataFrame(columns=self.column_names)
|
173 |
|
174 |
-
def extract_data_from_message(self,
|
175 |
"""
|
176 |
Extracts data from the message payload and returns a dataframe.
|
177 |
|
@@ -181,17 +160,27 @@ class VAVPipeline:
|
|
181 |
Returns:
|
182 |
pd.DataFrame: The extracted data as a dataframe.
|
183 |
"""
|
184 |
-
payload = json.loads(message.payload.decode())
|
185 |
-
df = pd.DataFrame.from_dict(payload, orient="index").T
|
186 |
if self.get_cols == True:
|
187 |
self.get_input_output(df)
|
188 |
self.get_cols = False
|
|
|
189 |
df = df[self.column_names]
|
190 |
-
self.df.loc[len(self.df)] = df.values[0]
|
191 |
|
192 |
-
|
|
|
|
|
|
|
|
|
|
|
193 |
|
194 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
"""
|
196 |
Fits the model with the extracted data and returns the prepared input and transformed data.
|
197 |
|
@@ -201,12 +190,12 @@ class VAVPipeline:
|
|
201 |
Returns:
|
202 |
tuple: A tuple containing the prepared input and transformed data.
|
203 |
"""
|
204 |
-
|
205 |
|
206 |
-
df_window = self.get_window(df)
|
207 |
if df_window is not None:
|
208 |
df_trans = self.transform_window(df_window)
|
209 |
df_new = self.prepare_input(df_trans)
|
|
|
210 |
else:
|
211 |
df_new = None
|
212 |
df_trans = None
|
|
|
39 |
if rtu_id == 1:
|
40 |
self.zones = [69, 68, 67, 66, 65, 64, 42, 41, 40, 39, 38, 37, 36]
|
41 |
if rtu_id == 2:
|
42 |
+
self.zones = [72, 71, 63, 62, 60, 59, 58,57, 50, 49, 44, 43, 35, 34, 33, 32, 31, 30, 29, 28]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
self.output_col_names = []
|
45 |
self.input_col_names = [
|
|
|
150 |
self.num_outputs = len(self.output_col_names)
|
151 |
self.df = pd.DataFrame(columns=self.column_names)
|
152 |
|
153 |
+
def extract_data_from_message(self, df: pd.DataFrame):
|
154 |
"""
|
155 |
Extracts data from the message payload and returns a dataframe.
|
156 |
|
|
|
160 |
Returns:
|
161 |
pd.DataFrame: The extracted data as a dataframe.
|
162 |
"""
|
|
|
|
|
163 |
if self.get_cols == True:
|
164 |
self.get_input_output(df)
|
165 |
self.get_cols = False
|
166 |
+
|
167 |
df = df[self.column_names]
|
|
|
168 |
|
169 |
+
len_df = len(self.df)
|
170 |
+
|
171 |
+
if len_df != 0:
|
172 |
+
self.df = pd.concat([self.df, df], axis=0)
|
173 |
+
else:
|
174 |
+
self.df = df
|
175 |
|
176 |
+
if len_df > 31:
|
177 |
+
self.df = self.df.iloc[len_df - 31 : len_df]
|
178 |
+
self.df.loc[len_df] = self.df.mean()
|
179 |
+
return self.df
|
180 |
+
else:
|
181 |
+
return None
|
182 |
+
|
183 |
+
def fit(self, df: pd.DataFrame):
|
184 |
"""
|
185 |
Fits the model with the extracted data and returns the prepared input and transformed data.
|
186 |
|
|
|
190 |
Returns:
|
191 |
tuple: A tuple containing the prepared input and transformed data.
|
192 |
"""
|
193 |
+
df_window = self.extract_data_from_message(df)
|
194 |
|
|
|
195 |
if df_window is not None:
|
196 |
df_trans = self.transform_window(df_window)
|
197 |
df_new = self.prepare_input(df_trans)
|
198 |
+
|
199 |
else:
|
200 |
df_new = None
|
201 |
df_trans = None
|
src/vav/models/kmeans_vav_1.pkl
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:eac01ceecdae11713ee21462a8bd3dc7ea32e740c3daa42795b266a05e7c424a
|
3 |
+
size 1567961
|
src/vav/models/kmeans_vav_2.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:874aa63843989880be0b133e3de125c60ec4290146e152685a0ba09faf101f71
|
3 |
+
size 1567961
|
src/vav/models/kmeans_vav_3.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:086d45b9d2c98baaea5b0588cd6d228d84eb141b707fe845b11316b3ddc58774
|
3 |
+
size 1568153
|
src/vav/models/kmeans_vav_4.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:086d45b9d2c98baaea5b0588cd6d228d84eb141b707fe845b11316b3ddc58774
|
3 |
+
size 1568153
|
src/vav/models/lstm_vav_02.keras
ADDED
Binary file (658 kB). View file
|
|
src/vav/models/lstm_vav_03.keras
ADDED
Binary file (658 kB). View file
|
|
src/vav/models/lstm_vav_04.keras
ADDED
Binary file (658 kB). View file
|
|
src/vav/models/pca_vav_1.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:00484ce0c76fc9df1f8f119325a12ec7be5baf8879d4ac192448b2d7ba397c7e
|
3 |
+
size 1323
|
src/vav/models/pca_vav_2.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bf25a096656f207f218cc87347f126c2cae81a0bbe45fea6a8c144922dc6eeab
|
3 |
+
size 1371
|
{physLSTM → src/vav/models}/scaler_vav_2.pkl
RENAMED
File without changes
|
src/vav/models/scaler_vav_3.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:293ee3c9082e7104dfc96425cecad2a44e5914bbd1f43c25a0fd8c36507b103a
|
3 |
+
size 1925
|
src/vav/models/scaler_vav_4.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:293ee3c9082e7104dfc96425cecad2a44e5914bbd1f43c25a0fd8c36507b103a
|
3 |
+
size 1925
|