-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathantares.py
301 lines (238 loc) Β· 11.1 KB
/
antares.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import streamlit as st
import requests
import pandas as pd
import json
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import folium
from streamlit_folium import st_folium
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score, confusion_matrix, mean_squared_error
# ======= 1. Load Data dari Excel =======
df = pd.read_excel("Data.xlsx", engine="openpyxl")
# Pastikan semua kolom yang dibutuhkan ada
required_columns = {'Suhu (Β°C)', 'Kelembapan (%)', 'Kecepatan Angin (Km/h)', 'Decision Tree', 'NaΓ―ve Bayes'}
# Pastikan data memiliki kolom yang sesuai
if required_columns.issubset(df.columns):
le = LabelEncoder()
df[['Decision Tree', 'NaΓ―ve Bayes']] = df[['Decision Tree', 'NaΓ―ve Bayes']].apply(le.fit_transform)
# Pisahkan fitur dan target
X = df[['Suhu (Β°C)', 'Kelembapan (%)', 'Kecepatan Angin (Km/h)']]
y1 = df['Decision Tree']
y2 = df['NaΓ―ve Bayes']
# Split data training dan testing
X_train, X_test, y1_train, y1_test, y2_train, y2_test = train_test_split(
X, y1, y2, test_size=0.2, random_state=42
)
# Buat model Decision Tree & Naive Bayes
dt_model = DecisionTreeClassifier()
dt_model.fit(X_train, y1_train)
nb_model = GaussianNB()
nb_model.fit(X_train, y2_train)
# Konfigurasi sesi HTTP dengan retry untuk koneksi yang lebih stabil
session = requests.Session()
retry = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
session.mount("https://", HTTPAdapter(max_retries=retry))
# === Konfigurasi Antares HTTP ===
ACCESSKEY = st.secrets["ACCESSKEY"]
PROJECT_NAME = "SistemMonitoringCuaca"
DEVICE_NAME = "ESP32"
URL_LATEST = f"https://platform.antares.id:8443/~/antares-cse/antares-id/{PROJECT_NAME}/{DEVICE_NAME}/la"
URL_HISTORY = f"https://platform.antares.id:8443/~/antares-cse/antares-id/{PROJECT_NAME}/{DEVICE_NAME}?rcn=4&ty=4&fu=1&lim=10"
URL_BASE = "https://platform.antares.id:8443"
headers = {
"X-M2M-Origin": ACCESSKEY,
"Content-Type": "application/json",
"Accept": "application/json"
}
# === Fungsi Mengambil Data Terbaru dari Antares ===
def get_latest_data():
try:
response = session.get(URL_LATEST, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
return json.loads(data["m2m:cin"]["con"]) # Konversi string JSON ke dictionary
except requests.exceptions.RequestException as e:
st.error(f"Error fetching latest data: {e}")
return None
# === Fungsi Mengambil Data Riwayat ===
def get_history_data():
try:
response = requests.get(URL_HISTORY, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
if "m2m:uril" not in data:
return None
history = []
for uri in data["m2m:uril"]:
data_response = requests.get(f"{URL_BASE}/~{uri}", headers=headers, timeout=10)
data_response.raise_for_status()
data_content = data_response.json()
if "m2m:cin" in data_content:
content = json.loads(data_content["m2m:cin"]["con"])
content["timestamp"] = data_content["m2m:cin"]["ct"]
history.append(content)
return pd.DataFrame(history) if history else None
except requests.exceptions.RequestException as e:
st.error(f"Error fetching history data: {e}")
return None
# Menu navigasi di sidebar
st.sidebar.title("π€ Sistem Monitoring Cuaca")
# State untuk menyimpan menu yang dipilih
if "selected_menu" not in st.session_state:
st.session_state.selected_menu = "Dashboard π "
# Fungsi untuk mengubah menu saat tombol ditekan
def set_menu(menu_name):
st.session_state.selected_menu = menu_name
# Tombol Sidebar
if st.sidebar.button("Dashboard π ", use_container_width=True):
set_menu("Dashboard π ")
if st.sidebar.button("Lokasi π", use_container_width=True):
set_menu("Lokasi π")
if st.sidebar.button("Data Cuaca π", use_container_width=True):
set_menu("Data Cuaca π")
if st.sidebar.button("Evaluasi Model π", use_container_width=True):
set_menu("Evaluasi Model π")
# --- Tampilan Konten Berdasarkan Menu ---
st.title(st.session_state.selected_menu)
if st.session_state.selected_menu == "Dashboard π ":
st.markdown(
"""
<style>
.stApp{
background-color: #d0eced; /* Warna latar belakang */
}
</style>
""",
unsafe_allow_html=True
)
data = get_latest_data()
if data:
# Tampilan bersampingan dengan tinggi yang sejajar
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("<h3 style='text-align: center;'>π‘ Suhu</h3>", unsafe_allow_html=True)
st.markdown(f"<h2 style='text-align: center; font-weight: bold;'>{data['Suhu (Β°C)']:.2f}Β°C</h2>", unsafe_allow_html=True)
with col2:
st.markdown("<h3 style='text-align: center;'>π§ Kelembapan</h3>", unsafe_allow_html=True)
st.markdown(f"<h2 style='text-align: center; font-weight: bold;'>{data['Kelembapan (%)']:.2f}%</h2>", unsafe_allow_html=True)
with col3:
st.markdown("<h3 style='text-align: center;'>πͺοΈ Angin</h3>", unsafe_allow_html=True)
st.markdown(f"<h2 style='text-align: center; font-weight: bold;'>{data['Kecepatan Angin (Km/h)']:.2f} km/h</h2>", unsafe_allow_html=True)
st.markdown("<br><br>", unsafe_allow_html=True)
# Cuaca Real Time
st.header("Cuaca Realtime Area Polibatam π€οΈ")
col4, col5 = st.columns(2)
with col4:
st.markdown("<h3 style='text-align: center;'>π³ Decision Tree</h3>", unsafe_allow_html=True)
st.markdown(f"<h2 style='text-align: center; font-weight: bold;'>{data['Decision Tree']}</h2>", unsafe_allow_html=True)
with col5:
st.markdown("<h3 style='text-align: center;'>π² Naive Bayes</h3>", unsafe_allow_html=True)
st.markdown(f"<h2 style='text-align: center; font-weight: bold;'>{data['Naive Bayes']}</h2>", unsafe_allow_html=True)
st.markdown("<br><br>", unsafe_allow_html=True)
# Prediksi Cuaca 30 Menit Kedepan
suhu = data['Suhu (Β°C)']
kelembapan = data['Kelembapan (%)']
angin = data['Kecepatan Angin (Km/h)']
# Gunakan model untuk prediksi cuaca berdasarkan data real-time
input_data = [[suhu, kelembapan, angin]]
dt_pred = dt_model.predict(input_data)
nb_pred = nb_model.predict(input_data)
# Konversi hasil prediksi ke bentuk label
dt_result = le.inverse_transform(dt_pred)[0]
nb_result = le.inverse_transform(nb_pred)[0]
# Tambahkan hasil prediksi ke tampilan dashboard
st.header("Prediksi Cuaca 30 Menit Kedepan π€οΈ")
co24, co25 = st.columns(2)
with co24:
st.markdown("<h3 style='text-align: center;'>π³ Decision Tree</h3>", unsafe_allow_html=True)
st.markdown(f"<h2 style='text-align: center; font-weight: bold;'>{dt_result}</h2>", unsafe_allow_html=True)
with co25:
st.markdown("<h3 style='text-align: center;'>π² Naive Bayes</h3>", unsafe_allow_html=True)
st.markdown(f"<h2 style='text-align: center; font-weight: bold;'>{nb_result}</h2>", unsafe_allow_html=True)
st.markdown("<br><br>", unsafe_allow_html=True)
else:
st.error("β οΈ Gagal mengambil data terbaru dari Antares.")
elif st.session_state.selected_menu == "Lokasi π":
st.markdown(
"""
<style>
.stApp{
background-color: #d0eced; /* Warna latar belakang */
}
</style>
""",
unsafe_allow_html=True
)
latitude = 1.1187578768824524
longitude = 104.04846548164217
m = folium.Map(location=[latitude, longitude], zoom_start=15)
folium.Marker(
[latitude, longitude],
popup="Stasiun Cuaca",
tooltip="Klik untuk info",
icon=folium.Icon(icon="cloud", prefix="fa", color="red")
).add_to(m)
st_folium(m, width=900, height=600)
github_image_url_1 = "https://raw.githubusercontent.com/Rreso/monitoringcuaca/main/politeknik.jpg"
github_image_url_2 = "https://raw.githubusercontent.com/Rreso/monitoringcuaca/main/batam.jpg"
st.image(github_image_url_1, caption="Politeknik Negeri Batam", use_container_width=True)
st.image(github_image_url_2, caption="Rooftop Gedung Utama", use_container_width=True)
elif st.session_state.selected_menu == "Data Cuaca π":
st.markdown(
"""
<style>
.stApp{
background-color: #d0eced; /* Warna latar belakang */
}
</style>
""",
unsafe_allow_html=True
)
df_history = get_history_data()
if df_history is not None:
st.subheader("π Riwayat Data Cuaca (10 Data Terakhir)")
st.dataframe(df_history)
st.subheader("π Grafik Perubahan Cuaca")
st.line_chart(df_history.set_index("timestamp")[['Suhu (Β°C)', 'Kelembapan (%)', 'Kecepatan Angin (Km/h)']])
else:
st.warning("β οΈ Tidak ada data riwayat yang tersedia di Antares.")
elif st.session_state.selected_menu == "Evaluasi Model π":
st.markdown(
"""
<style>
.stApp{
background-color: #d0eced; /* Warna latar belakang */
}
</style>
""",
unsafe_allow_html=True
)
y1_pred = dt_model.predict(X_test) # Decision Tree
y2_pred = nb_model.predict(X_test) # NaΓ―ve Bayes
# === AKURASI ===
accuracy_dt = accuracy_score(y1_test, y1_pred)
accuracy_nb = accuracy_score(y2_test, y2_pred)
# === CONFUSION MATRIX ===
conf_matrix_dt = confusion_matrix(y1_test, y1_pred)
conf_matrix_nb = confusion_matrix(y2_test, y2_pred)
# === MSE & RMSE ===
mse_dt = mean_squared_error(y1_test, y1_pred)
rmse_dt = np.sqrt(mse_dt)
mse_nb = mean_squared_error(y2_test, y2_pred)
rmse_nb = np.sqrt(mse_nb)
st.subheader("π Evaluasi Model")
st.write(f"π― **Akurasi Decision Tree**: {accuracy_dt:.2f}")
st.write(f"π― **Akurasi NaΓ―ve Bayes**: {accuracy_nb:.2f}")
st.write("π **Confusion Matrix Decision Tree:**")
st.write(conf_matrix_dt)
st.write("π **Confusion Matrix NaΓ―ve Bayes:**")
st.write(conf_matrix_nb)
st.write(f"π **MSE Decision Tree**: {mse_dt:.4f}")
st.write(f"π **RMSE Decision Tree**: {rmse_dt:.4f}")
st.write(f"π **MSE NaΓ―ve Bayes**: {mse_nb:.4f}")
st.write(f"π **RMSE NaΓ―ve Bayes**: {rmse_nb:.4f}")