-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard_app.py
More file actions
290 lines (232 loc) · 10.9 KB
/
dashboard_app.py
File metadata and controls
290 lines (232 loc) · 10.9 KB
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
import customtkinter as ctk
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import joblib
import numpy as np
import pandas as pd
import datetime
import time
# --- CONFIGURATION ---
MODEL_PATH = 'pv_fault_model.joblib'
SCALER_PATH = 'pv_scaler.joblib'
FEATURE_NAMES = [f'I_V{i + 1}' for i in range(50)]
# --- THEME SETUP ---
ctk.set_appearance_mode("Dark")
ctk.set_default_color_theme("dark-blue")
class PVMonitorApp(ctk.CTk):
def __init__(self):
super().__init__()
# 1. Window Setup
self.title("SOLAR GUARD | Advanced AI Monitor")
self.geometry("1200x800")
# Load AI Model
self.load_system()
# State Variables
self.is_monitoring = False
self.current_curve = np.zeros(50) # For animation
self.target_curve = np.zeros(50) # For animation
# 2. GUI Layout
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
self.setup_sidebar()
self.setup_main_area()
def setup_sidebar(self):
# --- LEFT SIDEBAR ---
self.sidebar_frame = ctk.CTkFrame(self, width=220, corner_radius=0)
self.sidebar_frame.grid(row=0, column=0, sticky="nsew")
self.sidebar_frame.grid_rowconfigure(6, weight=1)
# Logo
self.logo_label = ctk.CTkLabel(self.sidebar_frame, text="SOLAR GUARD\nPRO",
font=ctk.CTkFont(size=22, weight="bold"))
self.logo_label.grid(row=0, column=0, padx=20, pady=(20, 10))
# Start/Stop
self.start_button = ctk.CTkButton(self.sidebar_frame, text="INITIATE SCAN", command=self.toggle_monitoring,
fg_color="#00cc66", font=ctk.CTkFont(weight="bold"))
self.start_button.grid(row=1, column=0, padx=20, pady=20)
# Noise Control
self.noise_label = ctk.CTkLabel(self.sidebar_frame, text="Signal Noise Injection:", anchor="w")
self.noise_label.grid(row=2, column=0, padx=20, pady=(10, 0))
self.noise_slider = ctk.CTkSlider(self.sidebar_frame, from_=0.0, to=1.0, number_of_steps=20)
self.noise_slider.grid(row=3, column=0, padx=20, pady=(0, 20))
self.noise_slider.set(0.05)
# STATIC MODEL SCORES PANEL
self.metrics_frame = ctk.CTkFrame(self.sidebar_frame, fg_color="#333333")
self.metrics_frame.grid(row=4, column=0, padx=10, pady=10, sticky="ew")
ctk.CTkLabel(self.metrics_frame, text="MODEL METRICS", font=ctk.CTkFont(size=12, weight="bold")).pack(pady=5)
self.acc_label = ctk.CTkLabel(self.metrics_frame, text="Training Acc: 100%", text_color="#00cc66")
self.acc_label.pack(pady=2)
self.f1_label = ctk.CTkLabel(self.metrics_frame, text="F1-Score: 1.00", text_color="#00cc66")
self.f1_label.pack(pady=2)
self.model_type_label = ctk.CTkLabel(self.metrics_frame, text="Arch: Random Forest", text_color="gray")
self.model_type_label.pack(pady=(2, 5))
# Event Log
self.log_label = ctk.CTkLabel(self.sidebar_frame, text="System Log:", anchor="w")
self.log_label.grid(row=5, column=0, padx=20, pady=(10, 0))
self.log_box = ctk.CTkTextbox(self.sidebar_frame, width=180)
self.log_box.grid(row=6, column=0, padx=10, pady=(0, 20), sticky="nsew")
def setup_main_area(self):
# --- MAIN CONTENT ---
self.main_frame = ctk.CTkFrame(self, fg_color="transparent")
self.main_frame.grid(row=0, column=1, sticky="nsew", padx=20, pady=20)
self.main_frame.grid_rowconfigure(1, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
# --- TOP PANEL: STATUS & SCORES ---
self.status_panel = ctk.CTkFrame(self.main_frame, height=120)
self.status_panel.grid(row=0, column=0, sticky="ew", pady=(0, 20))
self.status_panel.grid_columnconfigure(1, weight=1)
# Big Status Indicator
self.status_indicator = ctk.CTkButton(self.status_panel, text="STANDBY",
font=ctk.CTkFont(size=30, weight="bold"),
fg_color="gray", hover=False, height=80, width=250)
self.status_indicator.grid(row=0, column=0, padx=20, pady=20)
# Live Probabilities
self.scores_frame = ctk.CTkFrame(self.status_panel, fg_color="transparent")
self.scores_frame.grid(row=0, column=1, padx=20, sticky="ew")
# Normal Score Bar
self.lbl_norm = ctk.CTkLabel(self.scores_frame, text="Normal Probability: 0%")
self.lbl_norm.pack(anchor="w")
self.bar_norm = ctk.CTkProgressBar(self.scores_frame, progress_color="#00cc66")
self.bar_norm.pack(fill="x", pady=(0, 10))
self.bar_norm.set(0)
# Fault Score Bar
self.lbl_fault = ctk.CTkLabel(self.scores_frame, text="Fault Probability: 0%")
self.lbl_fault.pack(anchor="w")
self.bar_fault = ctk.CTkProgressBar(self.scores_frame, progress_color="#ff4d4d")
self.bar_fault.pack(fill="x")
self.bar_fault.set(0)
# --- BOTTOM PANEL: GRAPH ---
self.graph_frame = ctk.CTkFrame(self.main_frame)
self.graph_frame.grid(row=1, column=0, sticky="nsew")
self.setup_matplotlib()
def setup_matplotlib(self):
# Dark Theme Matplotlib
self.fig = Figure(figsize=(5, 4), dpi=100)
self.fig.patch.set_facecolor('#212121') # Matches CustomTkinter Dark
self.ax = self.fig.add_subplot(111)
self.ax.set_facecolor('#1a1a1a')
# Axis Styling
self.ax.spines['bottom'].set_color('white')
self.ax.spines['top'].set_color('white')
self.ax.spines['left'].set_color('white')
self.ax.spines['right'].set_color('white')
self.ax.tick_params(axis='x', colors='white')
self.ax.tick_params(axis='y', colors='white')
self.ax.set_title("Real-Time I-V Curve Signature", color='white', fontsize=12)
self.ax.set_xlabel("Sample Index", color='gray')
self.ax.grid(True, color='#333333', linestyle='--')
# Fixed limits to stop "jumping" axes
self.ax.set_ylim(-5, 9)
self.ax.set_xlim(0, 50)
# Plot Elements
self.line, = self.ax.plot([], [], color='#00ffcc', linewidth=2.5)
# Fill under curve (initialized empty)
self.fill = self.ax.fill_between(range(50), -5, -5, color='#00ffcc', alpha=0.1)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.graph_frame)
self.canvas.draw()
self.canvas.get_tk_widget().pack(fill="both", expand=True, padx=5, pady=5)
def load_system(self):
try:
self.model = joblib.load(MODEL_PATH)
self.scaler = joblib.load(SCALER_PATH)
print("System Loaded.")
except:
print("Models missing.")
exit()
def get_complex_reading(self):
# 1. Base Curves
curve_normal = np.linspace(0, 7, 50)
part1 = np.full(20, 3.15)
part2 = np.linspace(3.15, 0, 30)
curve_fault = np.concatenate([part1, part2])
# 2. Scenario
roll = np.random.rand()
if roll < 0.70:
base = curve_normal * np.random.uniform(0.9, 1.1)
label = "NORMAL"
elif roll < 0.90:
base = curve_fault * np.random.uniform(0.9, 1.1)
label = "FAULT"
else:
mix = np.random.uniform(0.3, 0.7)
base = (mix * curve_fault) + ((1 - mix) * curve_normal)
label = "AMBIGUOUS"
# 3. Noise
noise = np.random.normal(0, self.noise_slider.get(), 50)
return base + noise, label
def toggle_monitoring(self):
if not self.is_monitoring:
self.is_monitoring = True
self.start_button.configure(text="STOP SCAN", fg_color="#ff4d4d")
self.update_loop() # Start loop
else:
self.is_monitoring = False
self.start_button.configure(text="INITIATE SCAN", fg_color="#00cc66")
self.status_indicator.configure(text="STANDBY", fg_color="gray")
def animate_graph(self):
""" Smoothly morphs current_curve into target_curve over 10 steps """
if not self.is_monitoring: return
# Calculate one step of interpolation (Linear Interpolation)
step_size = 0.2 # 20% move per frame (Speed of morph)
diff = self.target_curve - self.current_curve
# If difference is negligible, stop animating this frame
if np.max(np.abs(diff)) < 0.05:
self.current_curve = self.target_curve
else:
self.current_curve = self.current_curve + (diff * step_size)
self.after(30, self.animate_graph) # Continue animation loop
# Update Plot
self.line.set_ydata(self.current_curve)
self.line.set_xdata(range(50))
# Update Fill (Remove old, add new)
try:
self.fill.remove()
except:
pass
# Dynamic Color based on value at index 30 (The "Dip" area)
val_at_30 = self.current_curve[30]
if val_at_30 < 1.0: # Faulty low
col = "#ff4d4d" # Red
elif val_at_30 < 2.5: # Ambiguous
col = "#ffcc00" # Yellow
else:
col = "#00ffcc" # Cyan/Green
self.line.set_color(col)
self.fill = self.ax.fill_between(range(50), -5, self.current_curve, color=col, alpha=0.15)
self.canvas.draw()
def update_loop(self):
if not self.is_monitoring: return
# 1. Get New Data Target
raw_data, real_status = self.get_complex_reading()
self.target_curve = raw_data
# 2. Trigger Smooth Animation
self.animate_graph()
# 3. Predict & Update Stats
df = pd.DataFrame([raw_data], columns=FEATURE_NAMES)
scaled = self.scaler.transform(df)
probs = self.model.predict_proba(scaled)[0] # [Prob_Normal, Prob_Fault]
prob_norm = probs[0]
prob_fault = probs[1]
# Update Bars
self.bar_norm.set(prob_norm)
self.lbl_norm.configure(text=f"Normal Probability: {prob_norm * 100:.1f}%")
self.bar_fault.set(prob_fault)
self.lbl_fault.configure(text=f"Fault Probability: {prob_fault * 100:.1f}%")
# Update Big Indicator
if prob_fault > 0.6:
self.status_indicator.configure(text="FAULT DETECTED", fg_color="#ff4d4d")
status_log = "FAULT"
elif prob_norm > 0.6:
self.status_indicator.configure(text="SYSTEM NORMAL", fg_color="#00cc66")
status_log = "NORMAL"
else:
self.status_indicator.configure(text="UNCERTAIN", fg_color="#ffcc00")
status_log = "UNCERTAIN"
# Log
t = datetime.datetime.now().strftime("%H:%M:%S")
self.log_box.insert("0.0", f"[{t}] {status_log} (Conf: {max(probs) * 100:.0f}%)\n")
# Schedule next major update in 2 seconds
self.after(2000, self.update_loop)
if __name__ == "__main__":
app = PVMonitorApp()
app.mainloop()