-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3255 lines (2843 loc) · 124 KB
/
main.py
File metadata and controls
3255 lines (2843 loc) · 124 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
FilantropiaSolar - Advanced Solar Energy Analysis Application
A comprehensive solar energy prediction and analysis tool for Portuguese PV
installations featuring interactive charts, historical analysis, and future
simulation capabilities.
Data Source Citation:
Sarmas, Elissaios; Matias, Nuno; Pereira, Catarina; Antunes, Ana Rita (2025),
"Photovoltaic Power Production Dataset", Mendeley Data, V3, doi: 10.17632/dbh93b6vp8.3
Author: FilantropiaSolar Team
Version: 1.2.3
"""
from datetime import datetime, timedelta
import logging
import queue
import sys
import threading
import tkinter as tk
from tkinter import messagebox, ttk
import traceback
from typing import Any
# Create logger early so import errors can be reported safely
logger = logging.getLogger(__name__)
import pandas as pd
# Robust import for path utilities (supports packaged and dev layouts)
try:
from filantropia_solar.utils.paths import get_resource_path, get_app_cache_dir
except Exception:
try:
from src.utils.paths import get_resource_path, get_app_cache_dir
except Exception:
from utils.paths import get_resource_path, get_app_cache_dir
# Remove sys.path manipulation - use proper package imports instead
# Project imports (prefer packaged namespace, fallback to src.* during dev)
try:
from filantropia_solar.data_processing.comprehensive_data_processor import (
ComprehensiveDataProcessor,
)
from filantropia_solar.prediction.enhanced_energy_predictor import (
EnhancedEnergyPredictor,
)
from filantropia_solar.prediction.weather_ranking_system import WeatherRankingSystem
from filantropia_solar.weather_simulation.weather_simulator import WeatherSimulator
except Exception:
try:
from src.data_processing.comprehensive_data_processor import (
ComprehensiveDataProcessor,
)
from src.prediction.enhanced_energy_predictor import (
EnhancedEnergyPredictor,
)
from src.prediction.weather_ranking_system import WeatherRankingSystem
from src.weather_simulation.weather_simulator import WeatherSimulator
except Exception as _import_err:
logger.error(f"Critical import failure: {_import_err}")
ComprehensiveDataProcessor = None # type: ignore[assignment]
WeatherSimulator = None # type: ignore[assignment]
EnhancedEnergyPredictor = None # type: ignore[assignment]
WeatherRankingSystem = None # type: ignore[assignment]
# Optional matplotlib imports
try:
from matplotlib.backends.backend_tkagg import ( # type: ignore[import-not-found]
FigureCanvasTkAgg,
NavigationToolbar2Tk,
)
from matplotlib.figure import Figure # type: ignore[import-not-found]
from matplotlib.patches import Patch, Rectangle # type: ignore[import-not-found]
import matplotlib.pyplot as plt # type: ignore[import-not-found]
except Exception:
plt = None # type: ignore[assignment]
Figure = None # type: ignore[assignment]
FigureCanvasTkAgg = None # type: ignore[assignment]
NavigationToolbar2Tk = None # type: ignore[assignment]
Rectangle = None # type: ignore[assignment]
Patch = None # type: ignore[assignment]
# Configure logger (handlers and levels are set in _setup_logging)
# Lint/clarity constants
MAX_ISSUES_PREVIEW = 5
DEFAULT_DAY_INDEX_MAX = 20
ENERGY_LABEL_THRESHOLD = 0.1
DEFAULT_PROD_HOUR_MIN = 6
DEFAULT_PROD_HOUR_MAX = 20
# GUI and Display constants
LOADING_WINDOW_WIDTH = 520
LOADING_WINDOW_HEIGHT = 320
ANALYSIS_PERIOD_DAYS = 21
CHART_PLACEHOLDER_SIZE = 0.5
CHART_Y_AXIS_PADDING = 1.2
LEGEND_BBOX_ANCHOR_X = 1.08
LEGEND_BBOX_ANCHOR_Y = 0.5
CHART_AXIS_PADDING = 0.5
MAX_CHART_TICKS = 8
# Data processing constants
RANKING_PERCENTILE_20 = 20
RANKING_PERCENTILE_40 = 40
RANKING_PERCENTILE_60 = 60
RANKING_PERCENTILE_80 = 80
DEFAULT_HUMIDITY = 50
DEFAULT_CLOUD_COVER = 50
DEFAULT_WIND_SPEED = 5
DEFAULT_SOLAR_RADIATION = 200
RADIATION_SCALE_FACTOR = 10
HUMIDITY_CLOUD_MAX = 100
HOUR_MIN = 0
HOUR_MAX = 23
HOUR_PADDING = 1
DATE_SAMPLE_LIMIT = 50
class FilantropiaSolarApp:
"""
Main application class for FilantropiaSolar enhanced solar energy analysis.
Features:
- Interactive hourly energy production charts
- Historical data analysis and future simulation
- Weather correlation analysis
- Performance rankings and insights
- Multi-installation support
"""
def __init__(self):
"""Initialize the FilantropiaSolar application."""
self._setup_logging()
# Core components (loaded progressively)
self.data_processor = None
self.weather_simulator = None
self.energy_predictor = None
self.weather_ranking_system = None
# GUI components
self.root = None
self.loading_frame = None
self.main_frame = None
self.progress_var = None
self.status_var = None
# Threading for non-blocking initialization
self.loading_queue = queue.Queue()
self.loading_thread = None
# Application state
self.is_initialized = False
self.current_results = None
self.current_day_index = ANALYSIS_PERIOD_DAYS // 2 # Start with center date
self.available_dates = {} # Store available dates per installation
self.cache_manager = None # Will be set after initialization
self.current_analysis_mode = None # Store current analysis mode
# Validation baseline (Lisbon 4-year hourly min/avg/max)
self.validation_baseline_df: pd.DataFrame | None = None
logger.info("FilantropiaSolar Application initialized")
def _setup_logging(self):
"""Setup logging configuration for the application."""
log_dir = get_app_cache_dir("logs")
# Directory ensured by helper, but keep mkdir for safety
log_dir.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
level=logging.WARNING,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(log_dir / "filantropia_solar.log"),
logging.StreamHandler(sys.stdout),
],
)
logger.setLevel(logging.INFO)
def create_loading_gui(self):
"""Create the initial loading interface."""
self.root = tk.Tk()
self.root.title("FilantropiaSolar v1.2.3 - Loading...")
self.root.geometry(f"{LOADING_WINDOW_WIDTH}x{LOADING_WINDOW_HEIGHT}")
self.root.resizable(False, False)
# Center the window
self.root.update_idletasks()
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
x = (screen_width - LOADING_WINDOW_WIDTH) // 2
y = (screen_height - LOADING_WINDOW_HEIGHT) // 2
self.root.geometry(f"{LOADING_WINDOW_WIDTH}x{LOADING_WINDOW_HEIGHT}+{x}+{y}")
# Main loading frame
self.loading_frame = ttk.Frame(self.root, padding="30")
self.loading_frame.pack(fill=tk.BOTH, expand=True)
# Application title and branding
title_label = ttk.Label(
self.loading_frame,
text="☀️ FilantropiaSolar v1.2.3",
font=("Arial", 20, "bold"),
)
title_label.pack(pady=(20, 5))
subtitle_label = ttk.Label(
self.loading_frame,
text="Advanced Solar Energy Analysis",
font=("Arial", 12, "italic"),
)
subtitle_label.pack(pady=(0, 20))
# Progress tracking
self.progress_var = tk.DoubleVar()
progress_bar = ttk.Progressbar(
self.loading_frame,
variable=self.progress_var,
maximum=100,
length=350,
mode="determinate",
)
progress_bar.pack(pady=10)
self.status_var = tk.StringVar(value="Initializing application...")
status_label = ttk.Label(
self.loading_frame,
textvariable=self.status_var,
font=("Arial", 10),
)
status_label.pack(pady=10)
# Feature overview
info_frame = ttk.Frame(self.loading_frame)
info_frame.pack(pady=(20, 0), fill=tk.BOTH, expand=True)
features_text = tk.Text(
info_frame,
height=7,
width=55,
wrap=tk.WORD,
font=("Arial", 9),
state="disabled",
bg=self.root.cget("bg"),
relief="flat",
)
features_text.pack()
features_text.config(state="normal")
features_text.insert(
tk.END,
"🔋 Loading comprehensive solar energy system v1.2.3...\n\n"
"✓ 9 PV installations across Portugal\n"
"✓ 315,567+ historical energy records\n"
"✓ Hourly production analysis with weather correlation\n"
"✓ Historical data exploration & future simulation\n"
"✓ Interactive charts with performance rankings\n"
"✓ Advanced machine learning predictions\n"
"✓ NEW: Enhanced code quality & performance optimization\n",
)
features_text.config(state="disabled")
self.root.protocol("WM_DELETE_WINDOW", self._on_loading_close)
def _on_loading_close(self):
"""Handle loading window close event."""
if messagebox.askyesno(
"Confirm Exit",
"Cancel loading and exit FilantropiaSolar?",
):
self._cleanup_and_exit()
def _create_cache_status_section(self, parent):
"""Create the System Status (cache status + controls) section inside parent."""
# Cache Status Display
cache_frame = ttk.LabelFrame(parent, text="System Status", padding="15")
cache_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 0))
self._create_cache_status_display(cache_frame)
def _create_cache_status_display(self, parent):
"""Create cache status display with management options."""
try:
if not self.cache_manager:
ttk.Label(parent, text="⚠️ Caching disabled", foreground="orange").pack(
anchor=tk.W,
)
return
status = self.cache_manager.get_cache_status()
# Status information frame
info_frame = ttk.Frame(parent)
info_frame.pack(fill=tk.X, pady=(0, 10))
# Cache statistics
ttk.Label(
info_frame,
text="📊 Cache Status:",
font=("Arial", 10, "bold"),
).pack(anchor=tk.W)
status_text = f"""• Data Cache: {status.get("data_cache", {}).get("cached_items", 0)} items ({status.get("data_cache", {}).get("size_mb", 0):.1f} MB)
• Model Cache: {status.get("model_cache", {}).get("cached_models", 0)} models ({status.get("model_cache", {}).get("size_mb", 0):.1f} MB)
• Total Size: {status.get("total_size_mb", 0):.1f} MB"""
ttk.Label(info_frame, text=status_text, font=("Arial", 9)).pack(
anchor=tk.W,
pady=(2, 0),
)
# Cache management buttons
buttons_frame = ttk.Frame(parent)
buttons_frame.pack(fill=tk.X)
ttk.Button(
buttons_frame,
text="🔄 Refresh Status",
command=self._refresh_cache_status,
width=15,
).pack(side=tk.LEFT, padx=(0, 5))
ttk.Button(
buttons_frame,
text="🧹 Clear Cache",
command=self._clear_cache_dialog,
width=15,
).pack(side=tk.LEFT, padx=(0, 5))
ttk.Button(
buttons_frame,
text="🔍 Validate Cache",
command=self._validate_cache,
width=15,
).pack(side=tk.LEFT)
except Exception as e:
logger.error(f"Error creating cache status display: {e}")
ttk.Label(
parent,
text=f"Error loading cache status: {e}",
foreground="red",
).pack(anchor=tk.W)
def _refresh_cache_status(self):
"""Refresh the cache status display."""
try:
# Find and update the cache frame
for child in self.main_frame.winfo_children():
if isinstance(child, ttk.Notebook):
for tab_id in child.tabs():
if "Configuration" in child.tab(tab_id, "text"):
# Find the cache frame and refresh it
self.input_status_var.set("Cache status refreshed")
self.root.after(
2000,
lambda: self.input_status_var.set(
"Ready to generate analysis",
),
)
break
except Exception as e:
logger.error(f"Error refreshing cache status: {e}")
def _clear_cache_dialog(self):
"""Show cache clearing dialog."""
try:
if not self.cache_manager:
messagebox.showwarning("Cache Management", "Cache is not enabled.")
return
result = messagebox.askyesnocancel(
"Clear Cache",
"Choose cache clearing option:\n\n"
"• Yes: Clear all cache (data + models)\n"
"• No: Clear only data cache\n"
"• Cancel: Keep cache unchanged",
)
if result is True: # Clear all
if self.cache_manager.clear_cache("all"):
messagebox.showinfo("Success", "All cache cleared successfully")
self.input_status_var.set(
"All cache cleared - next run will rebuild",
)
else:
messagebox.showerror("Error", "Failed to clear cache")
elif result is False: # Clear data only
if self.cache_manager.clear_cache("data"):
messagebox.showinfo("Success", "Data cache cleared successfully")
self.input_status_var.set("Data cache cleared - models preserved")
else:
messagebox.showerror("Error", "Failed to clear data cache")
except Exception as e:
logger.error(f"Error in cache clear dialog: {e}")
messagebox.showerror("Error", f"Cache operation failed: {e}")
def _validate_cache(self):
"""Validate cache integrity."""
try:
if not self.cache_manager:
messagebox.showwarning("Cache Management", "Cache is not enabled.")
return
self.input_status_var.set("Validating cache integrity...")
self.root.update_idletasks()
results = self.cache_manager.validate_cache()
if results.get("issues"):
issues_text = "\n".join(results["issues"][:MAX_ISSUES_PREVIEW])
if len(results["issues"]) > MAX_ISSUES_PREVIEW:
issues_text += f"\n... and {len(results['issues']) - MAX_ISSUES_PREVIEW} more issues"
messagebox.showwarning(
"Cache Validation",
f"Found {len(results['issues'])} issues:\n\n{issues_text}",
)
else:
messagebox.showinfo(
"Cache Validation",
f"Cache validation successful!\n\n"
f"Valid entries: {results.get('valid_entries', 0)}\n"
f"No issues found.",
)
self.input_status_var.set("Cache validation completed")
self.root.after(
3000,
lambda: self.input_status_var.set("Ready to generate analysis"),
)
except Exception as e:
logger.error(f"Error validating cache: {e}")
messagebox.showerror("Error", f"Cache validation failed: {e}")
self.input_status_var.set("Cache validation failed")
def _cleanup_and_exit(self):
"""Perform cleanup and exit the application."""
try:
if self.loading_thread and self.loading_thread.is_alive():
# Allow thread to finish naturally
pass
if self.root:
self.root.quit()
self.root.destroy()
except Exception as e:
logger.error(f"Error during cleanup: {e}")
finally:
sys.exit(0)
def _update_progress(self, value: float, status: str):
"""Update the progress bar and status message."""
self.progress_var.set(value)
self.status_var.set(status)
self.root.update_idletasks()
def _initialize_components_threaded(self):
"""Initialize all application components in a separate thread."""
try:
# Step 1: Load data processing system
self._update_progress(15, "Loading installation data...")
self.data_processor = ComprehensiveDataProcessor()
# Store cache manager reference
self.cache_manager = getattr(self.data_processor, "cache_manager", None)
# Step 2: Analyze available data ranges
self._update_progress(35, "Analyzing available data ranges...")
self._load_available_dates()
# Load validation baseline (Lisbon 4-year averages)
self._update_progress(45, "Loading validation baseline (Lisbon averages)...")
self._load_validation_baseline()
# Step 3: Initialize weather simulation
self._update_progress(55, "Initializing weather simulation...")
self.weather_simulator = WeatherSimulator("weather_files")
# Step 4: Initialize ML models (try loading existing first)
self._update_progress(75, "Initializing machine learning models...")
self.energy_predictor = EnhancedEnergyPredictor(
self.data_processor,
self.weather_simulator,
)
# Initialize weather ranking system
self.weather_ranking_system = WeatherRankingSystem(
self.energy_predictor,
self.data_processor,
)
# Try to load models saved on disk (optional); otherwise predictor uses cache or trains on demand
try:
self.energy_predictor.load_models()
logger.info("Attempted to load on-disk ML models (optional)")
self._update_progress(95, "Checking existing ML models...")
except Exception as e:
logger.warning(
f"Model load attempt skipped/failed: {e}. Will train or use cache automatically.",
)
self._update_progress(90, "Preparing ML models...")
# Step 5: Finalize setup
self._update_progress(98, "Finalizing setup...")
self._update_progress(100, "Initialization complete!")
# Signal successful completion
self.loading_queue.put("COMPLETE")
except Exception as e:
logger.error(f"Error during initialization: {e}")
self.loading_queue.put(f"ERROR: {e!s}")
def _load_available_dates(self):
"""Load available date ranges for each installation."""
try:
installations = self.data_processor.get_installation_list()
for inst_id, info in installations:
try:
# Attempt to get installation data
data = self.data_processor.get_combined_data(inst_id)
if data is not None and not data.empty:
min_date = data.index.min().date()
max_date = data.index.max().date()
self.available_dates[inst_id] = {
"min_date": min_date,
"max_date": max_date,
"location": info.location,
"serial": info.serial_number,
}
except Exception as data_error:
logger.warning(
f"Could not load dates for installation {inst_id}: {data_error}",
)
# Set reasonable default date range
self.available_dates[inst_id] = {
"min_date": datetime(2023, 1, 1).date(),
"max_date": datetime(2024, 12, 31).date(),
"location": info.location,
"serial": info.serial_number,
}
logger.info(
f"Loaded available dates for {len(self.available_dates)} installations",
)
except Exception as e:
logger.error(f"Error loading available dates: {e}")
def _start_loading(self):
"""Start the loading process in a separate thread."""
self.loading_thread = threading.Thread(
target=self._initialize_components_threaded,
)
self.loading_thread.daemon = True
self.loading_thread.start()
self._check_loading_progress()
def _check_loading_progress(self):
"""Check loading progress and handle completion/errors."""
try:
message = self.loading_queue.get_nowait()
if message == "COMPLETE":
self._on_loading_complete()
elif message.startswith("ERROR:"):
self._on_loading_error(message[6:]) # Remove "ERROR:" prefix
except queue.Empty:
# Continue checking
self.root.after(100, self._check_loading_progress)
except Exception as e:
logger.error(f"Error checking loading progress: {e}")
self._on_loading_error(str(e))
def _on_loading_complete(self):
"""Handle successful loading completion."""
try:
self.is_initialized = True
logger.info("All components initialized successfully")
# Brief pause to show completion
self.root.after(1000, self._transition_to_main_gui)
except Exception as e:
logger.error(f"Error handling loading completion: {e}")
self._on_loading_error(str(e))
def _on_loading_error(self, error_message: str):
"""Handle loading errors."""
logger.error(f"Loading failed: {error_message}")
self.status_var.set("Loading failed!")
self.progress_var.set(0)
messagebox.showerror(
"Loading Failed",
f"Failed to initialize FilantropiaSolar:\n\n{error_message}\n\n"
"Please check the logs directory for more details.",
)
self._cleanup_and_exit()
def _transition_to_main_gui(self):
"""Transition from loading screen to main application interface."""
try:
# Remove loading interface
self.loading_frame.destroy()
# Reconfigure main window
self.root.title("FilantropiaSolar v1.2.3 - Advanced Solar Energy Analysis")
self.root.geometry("1400x900")
self.root.resizable(True, True)
# Create main interface
self._create_main_gui()
self._show_welcome_message()
except Exception as e:
logger.error(f"Error transitioning to main GUI: {e}")
messagebox.showerror(
"Interface Error",
f"Failed to create main interface:\n{e!s}",
)
self._cleanup_and_exit()
def _create_main_gui(self):
"""Create the main application interface with tabs."""
self.main_frame = ttk.Frame(self.root, padding="10")
self.main_frame.pack(fill=tk.BOTH, expand=True)
# Create tabbed interface
notebook = ttk.Notebook(self.main_frame)
notebook.pack(fill=tk.BOTH, expand=True)
# Input & Configuration tab
input_frame = ttk.Frame(notebook)
notebook.add(input_frame, text="🎯 Analysis Configuration")
self._create_input_interface(input_frame)
# Results tab
results_frame = ttk.Frame(notebook)
notebook.add(results_frame, text="📋 Analysis Results")
self._create_results_interface(results_frame)
# Interactive Charts tab
charts_frame = ttk.Frame(notebook)
notebook.add(charts_frame, text="📊 Interactive Charts")
self._create_charts_interface(charts_frame)
# Configure window close behavior
self.root.protocol("WM_DELETE_WINDOW", self._on_main_close)
def _create_input_interface(self, parent):
"""Create the analysis configuration interface."""
container = ttk.Frame(parent, padding="20")
container.pack(fill=tk.BOTH, expand=True)
# Create all sections
self._create_header_section(container)
self._create_mode_selection_section(container)
self._create_installation_selection_section(container)
# Row: Date Selection | System Status (side-by-side)
row_frame = ttk.Frame(container)
row_frame.pack(fill=tk.BOTH, expand=True)
row_frame.columnconfigure(0, weight=1)
row_frame.columnconfigure(1, weight=1)
left_frame = ttk.Frame(row_frame)
left_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
right_frame = ttk.Frame(row_frame)
right_frame.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
self._create_date_selection_section(left_frame)
self._create_cache_status_section(right_frame)
# Options and action buttons
self._create_options_and_buttons_section(container)
# Ready/status message below
self.input_status_var = tk.StringVar(value="Ready to generate analysis")
status_label = ttk.Label(
container,
textvariable=self.input_status_var,
foreground="goldenrod",
)
status_label.pack(pady=(10, 0))
# Initialize interface
self._on_mode_change()
self._on_installation_change()
def _create_header_section(self, container):
"""Create the header section with title."""
title_label = ttk.Label(
container,
text="Solar Energy Analysis Configuration",
font=("Arial", 16, "bold"),
)
title_label.pack(pady=(0, 20))
def _create_mode_selection_section(self, container):
"""Create the analysis mode selection section."""
mode_frame = ttk.LabelFrame(container, text="Analysis Mode", padding="15")
mode_frame.pack(fill=tk.X, pady=(0, 15))
self.mode_var = tk.StringVar(value="historical")
ttk.Radiobutton(
mode_frame,
text="📈 Historical Analysis (analyze existing data)",
variable=self.mode_var,
value="historical",
command=self._on_mode_change,
).pack(anchor=tk.W, pady=(0, 5))
ttk.Radiobutton(
mode_frame,
text="🔮 Future Simulation (predict any date)",
variable=self.mode_var,
value="simulation",
command=self._on_mode_change,
).pack(anchor=tk.W)
def _create_installation_selection_section(self, container):
"""Create the installation selection section with custom-station panel."""
frame = ttk.LabelFrame(
container,
text="Installation Selection",
padding="15",
)
frame.pack(fill=tk.X, pady=(0, 15))
# Two-column layout: Existing | Custom Station
frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, weight=1)
# Left: existing installations
left = ttk.Frame(frame)
left.grid(row=0, column=0, sticky="nsew", padx=(0, 8))
ttk.Label(left, text="Choose Installation:").pack(anchor=tk.W)
installations = self.data_processor.get_installation_list()
installation_options = [
f"{info.location}_{info.serial_number} ({info.installed_power_kwp} kWp)"
for _, info in installations
]
self.installation_var = tk.StringVar(
value=installation_options[0] if installation_options else "",
)
installation_combo = ttk.Combobox(
left,
textvariable=self.installation_var,
values=installation_options,
state="readonly",
width=60,
)
installation_combo.pack(fill=tk.X, pady=(5, 0))
installation_combo.bind("<<ComboboxSelected>>", self._on_installation_change)
# Right: custom station simulation
right = ttk.LabelFrame(frame, text="Custom Station (Simulation)")
right.grid(row=0, column=1, sticky="nsew", padx=(8, 0))
# Keep a reference for show/hide based on mode
self.custom_panel_frame = right
self.custom_use_var = tk.BooleanVar(value=False)
use_cb = ttk.Checkbutton(
right,
text="Simulate as new station",
variable=self.custom_use_var,
)
use_cb.pack(anchor=tk.W)
# Locations from known set (from existing installations)
unique_locations = sorted({info.location for _, info in installations}) or [
"Lisbon",
"Setubal",
"Faro",
"Braga",
"Tavira",
"Loule",
]
ttk.Label(right, text="Location:").pack(anchor=tk.W, pady=(6, 0))
self.custom_location_var = tk.StringVar(value=unique_locations[0])
loc_combo = ttk.Combobox(
right,
textvariable=self.custom_location_var,
values=unique_locations,
state="readonly",
width=30,
)
loc_combo.pack(anchor=tk.W, pady=(2, 4))
ttk.Label(right, text="Capacity (kWp):").pack(anchor=tk.W)
self.custom_capacity_var = tk.StringVar(value="5.0")
cap_entry = ttk.Entry(right, textvariable=self.custom_capacity_var, width=12)
cap_entry.pack(anchor=tk.W, pady=(2, 0))
def _create_date_selection_section(self, container):
"""Create the date selection section."""
self.date_frame = ttk.LabelFrame(container, text="Date Selection", padding="15")
self.date_frame.pack(fill=tk.X, pady=(0, 15))
# Historical date selection frame
self.historical_date_frame = ttk.Frame(self.date_frame)
self.historical_date_frame.pack(fill=tk.X)
ttk.Label(self.historical_date_frame, text="Available Data Range:").pack(
anchor=tk.W,
)
self.date_range_label = ttk.Label(
self.historical_date_frame,
text="Select an installation first",
foreground="gray",
)
self.date_range_label.pack(anchor=tk.W, pady=(2, 10))
ttk.Label(self.historical_date_frame, text="Select Historical Date:").pack(
anchor=tk.W,
)
self.historical_date_var = tk.StringVar()
self.historical_date_combo = ttk.Combobox(
self.historical_date_frame,
textvariable=self.historical_date_var,
state="readonly",
width=20,
)
self.historical_date_combo.pack(anchor=tk.W, pady=(5, 0))
# Simulation date selection frame
self.simulation_date_frame = ttk.Frame(self.date_frame)
ttk.Label(self.simulation_date_frame, text="Enter Date for Simulation:").pack(
anchor=tk.W,
)
self.simulation_date_var = tk.StringVar(
value=datetime.now().strftime("%Y-%m-%d"),
)
simulation_date_entry = ttk.Entry(
self.simulation_date_frame,
textvariable=self.simulation_date_var,
width=20,
)
simulation_date_entry.pack(anchor=tk.W, pady=(5, 0))
ttk.Label(
self.simulation_date_frame,
text="Format: YYYY-MM-DD (e.g., 2025-06-15)",
font=("Arial", 9),
foreground="gray",
).pack(anchor=tk.W, pady=(2, 0))
def _create_options_and_buttons_section(self, container):
"""Create the options and action buttons section."""
# Analysis Options
options_frame = ttk.LabelFrame(container, text="Options", padding="15")
options_frame.pack(fill=tk.X, pady=(0, 20))
# Weather source is automatic (API first, simulate gaps) — no manual toggle
self.simulation_var = tk.BooleanVar(value=True) # kept for backward compatibility
# (Checkbox removed from UI)
# Action Buttons Frame
buttons_frame = ttk.Frame(container)
buttons_frame.pack(pady=15)
# Main analysis button
predict_button = ttk.Button(
buttons_frame,
text="🚀 Generate 15-Day Analysis",
command=self._generate_analysis,
style="Accent.TButton",
)
predict_button.pack(side=tk.LEFT, padx=(0, 10))
# ML retrain button for advanced users
retrain_button = ttk.Button(
buttons_frame,
text="🔧 Retrain ML Models",
command=self._retrain_models,
style="TButton",
)
retrain_button.pack(side=tk.LEFT)
def _create_status_section(self, container):
"""Create the system status and ready message section (legacy layout)."""
# Cache Status Display
cache_frame = ttk.LabelFrame(container, text="System Status", padding="15")
cache_frame.pack(fill=tk.X, pady=(15, 0))
self._create_cache_status_display(cache_frame)
# Status Display
self.input_status_var = tk.StringVar(value="Ready to generate analysis")
status_label = ttk.Label(
container,
textvariable=self.input_status_var,
foreground="goldenrod",
)
status_label.pack(pady=(10, 0))
def _on_mode_change(self):
"""Handle analysis mode change."""
mode = self.mode_var.get()
if mode == "historical":
self.historical_date_frame.pack(fill=tk.X)
self.simulation_date_frame.pack_forget()
# Hide custom-station panel in historical mode
if hasattr(self, "custom_panel_frame") and self.custom_panel_frame.winfo_ismapped():
self.custom_panel_frame.grid_remove()
if hasattr(self, "custom_use_var"):
self.custom_use_var.set(False)
# Weather source automatic
self.simulation_var.set(True)
else:
self.simulation_date_frame.pack(fill=tk.X)
self.historical_date_frame.pack_forget()
# Show custom-station panel only in simulation mode
if hasattr(self, "custom_panel_frame") and not self.custom_panel_frame.winfo_ismapped():
self.custom_panel_frame.grid()
self.simulation_var.set(True)
def _on_installation_change(self, _event=None):
"""Handle installation selection change."""
try:
installation_text = self.installation_var.get()
if not installation_text:
return
# Find corresponding installation ID
installation_id = None
for inst_id, info in self.data_processor.get_installation_list():
if installation_text.startswith(
f"{info.location}_{info.serial_number}",
):
installation_id = inst_id
break
if installation_id and installation_id in self.available_dates:
date_info = self.available_dates[installation_id]
min_date = date_info["min_date"]
max_date = date_info["max_date"]
# Update date range display
days_available = (max_date - min_date).days
self.date_range_label.config(
text=f"{min_date} to {max_date} ({days_available:,} days available)",
foreground="goldenrod",
)
# Populate historical date options (sample to avoid overwhelming dropdown)
date_list = []
current = min_date
step_size = max(1, days_available // DATE_SAMPLE_LIMIT) # Limit to ~50 options
while current <= max_date:
date_list.append(current.strftime("%Y-%m-%d"))
current += timedelta(days=step_size)
# Ensure max date is included
if max_date.strftime("%Y-%m-%d") not in date_list:
date_list.append(max_date.strftime("%Y-%m-%d"))
self.historical_date_combo.config(values=date_list)
if date_list:
self.historical_date_var.set(
date_list[-1],
) # Default to most recent
except Exception as e:
logger.error(f"Error updating installation dates: {e}")
def _create_results_interface(self, parent):
"""Create the results display interface with split layout."""
container = ttk.Frame(parent, padding="10")
container.pack(fill=tk.BOTH, expand=True)
# Header
title_label = ttk.Label(
container,
text="Analysis Results",
font=("Arial", 16, "bold"),
)
title_label.pack(pady=(0, 10))