-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaterGen.py
More file actions
1713 lines (1482 loc) · 81.4 KB
/
WaterGen.py
File metadata and controls
1713 lines (1482 loc) · 81.4 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
# Grafische Benutzeroberfläche (GUI)
import tkinter as tk
from tkinter import ttk
from tkcalendar import DateEntry
import tksvg
from tkinter import filedialog # NEU: Für Verzeichnisauswahl
# Datenverarbeitung
import pandas as pd
import csv
import numpy as np
# Datums- und Zeitfunktionen
from datetime import datetime, timedelta
# Visualisierung
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# Bildverarbeitung
from PIL import Image, ImageTk, ImageDraw, ImageFont, ImageSequence
# Systemfunktionen
import threading
import os
import ctypes
from screeninfo import get_monitors
import webbrowser
import sys
# Mathematik und Zufall
import math
import random
# Verbesserte Farbpalette für konsistenten Darkmode
DISCORD_BG = "#3a393f"
DISCORD_DARK = "#2F3136"
DISCORD_DARKER = "#202225"
DISCORD_TEXT = "#FFFFFF"
DISCORD_GRAY_TEXT = "#96989D"
DISCORD_GREEN = "#4ee56e"
DISCORD_INPUT_BG = "#40444B"
BUTTON_COLOR = "#4ee56e"
BUTTON_HOVER = "#3aff58"
# Angepasste DateEntry-Klasse für Darkmode
class DarkDateEntry(DateEntry):
"""
Eine angepasste DateEntry-Klasse mit Darkmode-Styling.
"""
def __init__(self, master=None, **kw):
# Darkmode-Farbdefinitionen für den Kalender
dark_colors = {
'background': DISCORD_DARK, # Haupthintergrund
'foreground': DISCORD_TEXT, # Haupttext
'bordercolor': DISCORD_DARKER, # Rahmenfarbe
'headersbackground': DISCORD_DARKER, # Hintergrund der Kopfzeilen
'headersforeground': DISCORD_TEXT, # Text der Kopfzeilen
'selectbackground': DISCORD_GREEN, # Auswahlhintergrund
'selectforeground': 'white', # Auswahltext
'normalbackground': DISCORD_DARK, # Hintergrund normaler Tage
'normalforeground': DISCORD_TEXT, # Text normaler Tage
'weekendbackground': DISCORD_DARKER, # Hintergrund am Wochenende
'weekendforeground': DISCORD_TEXT, # Text am Wochenende
'othermonthbackground': '#2C2F33', # Hintergrund anderer Monate
'othermonthforeground': '#72767D' # Text anderer Monate
}
# Parameter mit dark_colors erweitern
for key, value in dark_colors.items():
if key not in kw:
kw[key] = value
# Eingabefeld-Farben
if 'background' not in kw:
kw['background'] = DISCORD_DARK
if 'foreground' not in kw:
kw['foreground'] = DISCORD_TEXT
if 'insertbackground' not in kw:
kw['insertbackground'] = DISCORD_TEXT # Cursor-Farbe
# Super-Konstruktor mit Darkmode-Parametern aufrufen
super().__init__(master, **kw)
# Dropdown-Button anpassen (dieser wird nach der Initialisierung erstellt)
for child in self.winfo_children():
if child.winfo_class() == 'Button':
child.configure(
background=DISCORD_DARK,
activebackground=DISCORD_GREEN,
foreground=DISCORD_TEXT,
activeforeground='white'
)
# Kalenderfenster konfigurieren, wenn es erstellt wird (bei Drop-down)
self.bind("<<DateEntryPopup>>", self._style_calendar_popup)
def _style_calendar_popup(self, event=None):
"""Style das Kalenderfenster, wenn es geöffnet wird"""
if hasattr(self, '_top_cal'):
self._top_cal.configure(background=DISCORD_DARKER)
# Untergeordnete Widgets im Kalender anpassen
for child in self._top_cal.winfo_children():
if child.winfo_class() == 'Label':
child.configure(background=DISCORD_DARKER, foreground=DISCORD_TEXT)
elif child.winfo_class() == 'Button':
child.configure(
background=DISCORD_DARK,
foreground=DISCORD_TEXT,
activebackground=DISCORD_GREEN,
activeforeground='white'
)
# Verbesserte DateEntry-Klasse mit deutscher Datumsanzeige und Autovervollständigung
class AutoDateEntry(DarkDateEntry):
"""
Erweitert die DarkDateEntry-Klasse um deutsche Datumsanzeige und
automatische Formatierung im Format dd.mm.yy
"""
def __init__(self, master=None, **kwargs):
# Deutsches Datumsformat als Standard setzen
kwargs['locale'] = 'de_DE'
kwargs['date_pattern'] = 'dd.mm.yy'
# Darkmode Stile für DateEntry
style_options = {
'background': DISCORD_INPUT_BG,
'foreground': DISCORD_TEXT,
'borderwidth': 0,
}
kwargs.update(style_options)
# Super-Konstruktor aufrufen
super().__init__(master, **kwargs)
# Events binden
self.bind("<KeyRelease>", self._format_date_entry)
# Überschreibe die ursprüngliche drop_down Methode
self._original_drop_down = self.drop_down
self.drop_down = self._safe_drop_down
self.last_value = ""
def _safe_drop_down(self):
"""Sichere Version der drop_down Methode mit korrekter Positionierung"""
try:
# Prüfe ob Kalender bereits existiert und sichtbar ist
if hasattr(self, '_top_cal') and self._top_cal and self._top_cal.winfo_exists():
if self._top_cal.winfo_viewable():
# Kalender ist bereits offen, schließe ihn
self._top_cal.withdraw()
return
else:
# Kalender existiert aber ist nicht sichtbar, zeige ihn
self._position_calendar()
self._top_cal.deiconify()
return
# Rufe die ursprüngliche Methode auf
self._original_drop_down()
# Nach dem Öffnen des Kalenders, positioniere ihn korrekt
if hasattr(self, '_top_cal') and self._top_cal:
self._position_calendar()
self._configure_calendar_popup()
except Exception as e:
print(f"Fehler beim Öffnen des Kalenders: {e}")
# Versuche den Kalender zurückzusetzen
self._reset_calendar()
def _position_calendar(self):
"""Positioniert das Kalender-Popup korrekt relativ zum DateEntry-Widget, unterstützt mehrere Monitore"""
try:
if not hasattr(self, '_top_cal') or not self._top_cal:
return
# Warte bis das Widget vollständig gerendert ist
self.update_idletasks()
# Position des DateEntry-Widgets ermitteln
x = self.winfo_rootx()
y = self.winfo_rooty()
# Höhe des DateEntry-Widgets
entry_height = self.winfo_height()
# Kalender unter dem DateEntry positionieren
calendar_x = x
calendar_y = y + entry_height + 2 # 2px Abstand
# Monitor ermitteln, auf dem sich das DateEntry-Widget befindet
monitor_info = self.winfo_toplevel().winfo_screen()
# Hole Informationen über alle verfügbaren Monitore
try:
monitors = get_monitors()
# Bestimme den aktuellen Monitor
current_monitor = None
widget_center_x = x + self.winfo_width() / 2
widget_center_y = y + self.winfo_height() / 2
for m in monitors:
if (m.x <= widget_center_x <= m.x + m.width and
m.y <= widget_center_y <= m.y + m.height):
current_monitor = m
break
if current_monitor:
screen_width = current_monitor.width
screen_height = current_monitor.height
screen_x = current_monitor.x
screen_y = current_monitor.y
else:
# Fallback zu Hauptbildschirm
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
screen_x = 0
screen_y = 0
except:
# Fallback falls screeninfo nicht verfügbar
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
screen_x = 0
screen_y = 0
# Kalender-Größe ermitteln
try:
self._top_cal.update_idletasks()
calendar_width = self._top_cal.winfo_reqwidth()
calendar_height = self._top_cal.winfo_reqheight()
except:
calendar_width = 250 # Standardbreite
calendar_height = 200 # Standardhöhe
# Prüfe ob Kalender rechts über den Monitor hinausragen würde
if calendar_x + calendar_width > screen_x + screen_width:
calendar_x = screen_x + screen_width - calendar_width - 10
# Prüfe ob Kalender unten über den Monitor hinausragen würde
if calendar_y + calendar_height > screen_y + screen_height:
# Kalender über dem DateEntry positionieren
calendar_y = y - calendar_height - 2
# Falls auch oben nicht genug Platz ist
if calendar_y < screen_y:
calendar_y = screen_y + 10 # Mindestabstand vom oberen Bildschirmrand
# Stelle sicher, dass die Position innerhalb des Monitors liegt
calendar_x = max(screen_x, min(calendar_x, screen_x + screen_width - calendar_width))
calendar_y = max(screen_y, min(calendar_y, screen_y + screen_height - calendar_height))
# Kalender positionieren
self._top_cal.geometry(f"+{int(calendar_x)}+{int(calendar_y)}")
except Exception as e:
print(f"Fehler bei Kalender-Positionierung: {e}")
def _configure_calendar_popup(self):
"""Konfiguriert das Kalender-Popup nach dem Öffnen"""
try:
if hasattr(self, '_top_cal') and self._top_cal:
# Stelle sicher, dass das Popup fokussierbar ist
self._top_cal.focus_set()
# Bringe das Fenster in den Vordergrund
self._top_cal.lift()
self._top_cal.attributes('-topmost', True)
self._top_cal.attributes('-topmost', False)
# Stelle sicher, dass das Fenster nicht minimiert werden kann
self._top_cal.resizable(False, False)
except Exception as e:
print(f"Fehler bei Kalender-Konfiguration: {e}")
def _reset_calendar(self):
"""Setzt den Kalender zurück bei Problemen"""
try:
if hasattr(self, '_top_cal') and self._top_cal:
self._top_cal.destroy()
delattr(self, '_top_cal')
except:
pass
def _format_date_entry(self, event):
"""Automatische Formatierung der Datumseingabe"""
if event.keysym in ('BackSpace', 'Delete', 'Left', 'Right', 'Up', 'Down'):
self.last_value = self.get()
return
current = self.get()
def format_complete_date():
filtered = ''.join(c for c in current if c.isdigit() or c == '.')
parts = filtered.split('.')
if len(parts) != 3:
return None
day, month, year = parts
# Tag formatieren
try:
day_val = max(1, min(31, int(day))) if day else 1
day = str(day_val).zfill(2)
# Monat formatieren
month_val = max(1, min(12, int(month))) if month else 1
month = str(month_val).zfill(2)
# Jahr intelligent formatieren
current_year = datetime.now().year
current_century = current_year // 100
if len(year) == 1:
year = f"0{year}" # Immer zweistellig machen
elif len(year) == 2:
# Intelligente Jahrhundertwahl
year_num = int(year)
if year_num > (current_year % 100) + 20: # Wenn mehr als 20 Jahre in Zukunft
year = f"{current_century-1}{year}"
else:
year = f"{current_century}{year}"
elif len(year) == 3:
year = f"{current_century}{year[-2:]}"
elif len(year) > 4:
year = year[:4]
return f"{day}.{month}.{year}"
except ValueError:
return None
if event.type == '10': # FocusOut event
formatted = format_complete_date()
if formatted:
self.delete(0, tk.END)
self.insert(0, formatted)
self.last_value = formatted
return
# Normale Eingabe-Formatierung während des Tippens
filtered = ''.join(c for c in current if c.isdigit() or c == '.')
parts = filtered.split('.')
if len(parts) == 1 and parts[0]:
if len(parts[0]) == 2:
filtered = parts[0] + '.'
elif len(parts) == 2:
day, month = parts
if len(month) == 2:
filtered = day + '.' + month + '.'
self.delete(0, tk.END)
self.insert(0, filtered)
self.icursor(len(filtered))
self.last_value = filtered
# Dunkle Titelleiste für Windows
def set_dark_title_bar(window):
try:
window.update()
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
set_window_attribute = ctypes.windll.dwmapi.DwmSetWindowAttribute
get_parent = ctypes.windll.user32.GetParent
hwnd = get_parent(window.winfo_id())
value = ctypes.c_int(2)
set_window_attribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, ctypes.byref(value), ctypes.sizeof(value))
except Exception as e:
print(f"Fehler beim Setzen der dunklen Titelleiste: {e}")
# Funktion für abgerundete Rechtecke
def create_rounded_rect(canvas, x1, y1, x2, y2, radius=15, **kwargs):
points = [x1+radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y1+radius,
x1, y1]
return canvas.create_polygon(points, **kwargs, smooth=True)
# Die Formel-Parameter-Klasse (nur mit Grundwasser-Parametern)
class FormelParameter:
def __init__(self):
# Bestehende Parameter beibehalten
self.GW0 = 10.0 # Grundniveau in Meter unter GOK
self.A = 0.5 # Saisonale Amplitude
self.T = 365 # Periodendauer in Tagen
self.freq = 1.0 # Sinusfrequenz pro Periodendauer
self.Da = 45 # Anstiegsdauer in Tagen
self.Dd = 120 # Abklingdauer in Tagen
self.R_scale = 0.05 # Skalierung für zufällige Schwankungen
self.phase = 60 # Phasenverschiebung in Tagen
self.trend = 0.0 # Langzeittrend pro Jahr in Meter
# Neue Parameter für die gewünschten Funktionen
self.curve_randomness = 0.2 # Variabilität der Wellenform (0-1)
self.secondary_freq = 3.0 # Frequenz der überlagerten kleineren Wellen
def generiere_formel(self):
return (f"\n\t\t Ganglinien Layout bearbeiten\n")
# Funktion zur Berechnung der Grundwasserganglinie
def calculate_gw_series(t_array, GW0, A, T, freq, Da, Dd, R_scale, phase=60, trend=0.0, curve_randomness=0.2, secondary_freq=3.0):
# Seed setzen für reproduzierbare Ergebnisse
np.random.seed(42)
# R_base analog zur Vorschau erstellen
R_base = np.random.normal(0, 1, size=len(t_array))
# Stellen Sie sicher, dass T nicht Null ist, um Division durch Null zu vermeiden
if T == 0: T = 365 # Fallback-Wert
# Amplitudenvariationen für jeden Wellenzyklus
if curve_randomness > 0:
amplitude_variation = 1.0 + curve_randomness * np.random.normal(0, 1, size=len(t_array))
seasonal = A * np.sin(2 * np.pi * freq * (t_array - phase) / T) * amplitude_variation
else:
seasonal = A * np.sin(2 * np.pi * freq * (t_array - phase) / T)
# Sekundäre kleinere Wellen hinzufügen
if secondary_freq > 0:
small_waves = A * 0.3 * np.sin(2 * np.pi * secondary_freq * freq * t_array / T)
seasonal += small_waves
# Trend-Komponente hinzufügen
trend_component = trend * t_array / 365
base_level = GW0 + seasonal + trend_component
# Grundwasserstand initialisieren
GW = np.zeros_like(t_array, dtype=float)
if len(t_array) > 0:
GW[0] = GW0 + seasonal[0]
for i in range(1, len(t_array)):
disturbance = R_scale * R_base[i]
diff_from_GW0 = GW[i-1] - GW0
daily_change = 0
if disturbance > 0 and Da > 0:
daily_change = (disturbance - diff_from_GW0) / Da
elif Dd > 0:
daily_change = -diff_from_GW0 / Dd
GW[i] = GW[i-1] + daily_change
GW[i] += seasonal[i] - seasonal[i-1]
return GW
def create_csv_files(root, start_date, end_date, messstellen_ids, interval_hours, formel_params, progress, progress_info, output_directory):
hourly_interval = timedelta(hours=interval_hours)
delta = end_date - start_date
total_days = delta.days + 1
total_hours = total_days * 24
if interval_hours == 0: interval_hours = 1
# Correct calculation for total_measurements_per_station
_temp_current_time = start_date
_num_measurements = 0
while _temp_current_time <= end_date:
_num_measurements += 1
_temp_current_time += hourly_interval
total_measurements_per_station = _num_measurements
total_values = total_measurements_per_station * len(messstellen_ids)
t_days_array = np.arange(0, total_days, 1)
try:
grundwasser_series_daily = calculate_gw_series(
t_days_array,
formel_params.GW0,
formel_params.A,
formel_params.T,
formel_params.freq,
formel_params.Da,
formel_params.Dd,
formel_params.R_scale,
formel_params.phase,
formel_params.trend,
formel_params.curve_randomness,
formel_params.secondary_freq
)
except Exception as e:
print(f"Fehler bei Grundwasserreihen-Berechnung: {e}")
grundwasser_series_daily = np.full(total_days, formel_params.GW0)
values_created = 0
if not os.path.isdir(output_directory):
try:
os.makedirs(output_directory, exist_ok=True)
print(f"Ausgabeverzeichnis '{output_directory}' erstellt.")
except OSError as e:
print(f"Warnung: Ausgabeverzeichnis '{output_directory}' konnte nicht erstellt werden: {e}. Speichere im aktuellen Verzeichnis.")
progress_info.config(text="Warnung: Ausgabepfad ungültig/nicht erstellbar. Nutze aktuelles Verzeichnis.")
root.update_idletasks()
output_directory = "."
excel_file_created = False
if hasattr(root, 'output_format') and root.output_format == "excel":
all_data = {}
excel_filename = 'wasserstände_alle_messstellen.xlsx'
excel_filepath = os.path.join(output_directory, excel_filename)
root.partial_files_to_delete.append(excel_filepath)
for idx, messstelle_id in enumerate(messstellen_ids):
if root.cancel_generation_flag.is_set():
progress_info.config(text="Excel-Generierung wird abgebrochen...")
root.update_idletasks()
return
data = []
current_time = start_date
while current_time <= end_date:
if root.cancel_generation_flag.is_set():
progress_info.config(text="Excel-Generierung wird abgebrochen...")
root.update_idletasks()
return
# --- START: CALCULATION FOR messwert (copied and adapted from CSV part) ---
days_since_start = (current_time.date() - start_date.date()).days
tage_index = days_since_start
if 0 <= tage_index < len(grundwasser_series_daily):
basis_value = grundwasser_series_daily[tage_index]
else:
basis_value = formel_params.GW0
messstellen_offset = (idx - len(messstellen_ids) / 2) * 1.02 # Use idx from enumerate
messwert = basis_value + messstellen_offset
messwert += random.uniform(-formel_params.R_scale * 1.02, formel_params.R_scale * 1.02)
# --- END: CALCULATION FOR messwert ---
data.append([messstelle_id, current_time, float(f'{messwert:.2f}')]) # Use calculated messwert
current_time += hourly_interval
values_created += 1
if values_created % 100 == 0:
if total_values > 0 : progress['value'] = int((values_created / total_values) * 100)
else: progress['value'] = 0
progress_info.config(text=f"Werte generiert ({progress['value']}%)".replace(',', '.'))
root.update_idletasks()
if root.cancel_generation_flag.is_set(): return
all_data[messstelle_id] = data
if root.cancel_generation_flag.is_set(): return
try:
abs_output_dir = os.path.abspath(output_directory)
base_name_of_output_dir = os.path.basename(abs_output_dir)
display_folder_name = base_name_of_output_dir
if not display_folder_name:
if len(abs_output_dir) <= 3: display_folder_name = abs_output_dir
else: display_folder_name = "gewählten Ordner"
with pd.ExcelWriter(excel_filepath,
engine='xlsxwriter',
datetime_format='DD/MM/YYYY HH:MM') as writer: # Corrected datetime_format for Excel
for sheet_idx, (messstelle_id, data_list) in enumerate(all_data.items()):
if root.cancel_generation_flag.is_set(): return
df = pd.DataFrame(data_list, columns=['GWMST Name', 'Datum/Uhrzeit', 'Messwert'])
sheet_name = messstelle_id[:31] if len(messstelle_id) > 31 else messstelle_id
sheet_name = "".join([c for c in sheet_name if c.isalnum() or c in (' ', '_', '-')])
if not sheet_name or sheet_name[0] in ("'", "=") or any(char in sheet_name for char in ':\\/?*[]'):
sheet_name = f"Messstelle_{sheet_idx+1}"
df.to_excel(writer, sheet_name=sheet_name, index=False, header=False) # Header=False to match CSV
workbook = writer.book
worksheet = writer.sheets[sheet_name]
# Set column widths (optional, adjust as needed)
worksheet.set_column('A:A', len(messstelle_id) + 2 if len(messstelle_id) > 10 else 12) # GWMST Name
worksheet.set_column('B:B', 20) # Datum/Uhrzeit
worksheet.set_column('C:C', 12) # Messwert
if root.cancel_generation_flag.is_set(): return
excel_file_created = True
progress['value'] = 100
progress_info.config(text=f"Excel-Datei in Ordner '{display_folder_name}' gespeichert.")
root.update_idletasks()
except Exception as e:
if not root.cancel_generation_flag.is_set():
progress_info.config(text=f"Fehler beim Excel-Export: {str(e)}")
print(f"Excel Export Error: {e}")
finally:
if not excel_file_created and excel_filepath in root.partial_files_to_delete:
pass
elif excel_file_created and excel_filepath in root.partial_files_to_delete:
root.partial_files_to_delete.remove(excel_filepath)
else: # CSV-Export
num_messstellen_processed = len(messstellen_ids) # This was an error, should be len(messstellen_ids)
created_csv_files_successfully = []
for idx, messstelle_id in enumerate(messstellen_ids):
if root.cancel_generation_flag.is_set():
progress_info.config(text="CSV-Generierung wird abgebrochen...")
root.update_idletasks()
return
base_filename = f'wasserstände_{messstelle_id.replace(" ", "_")}.csv'
filepath = os.path.join(output_directory, base_filename)
root.partial_files_to_delete.append(filepath)
file_successfully_written = False
try:
with open(filepath, 'w', newline='', encoding='utf-8') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=';')
csvwriter.writerow(['GWMST Name', 'Datum/Zeit', 'Messwert']) # Header for CSV
current_time = start_date
while current_time <= end_date:
if root.cancel_generation_flag.is_set():
csvfile.close()
progress_info.config(text="CSV-Generierung wird abgebrochen...")
root.update_idletasks()
return
formatted_date = current_time.strftime("%d.%m.%Y %H:%M:%S")
days_since_start = (current_time.date() - start_date.date()).days
tage_index = days_since_start
if 0 <= tage_index < len(grundwasser_series_daily):
basis_value = grundwasser_series_daily[tage_index]
else:
basis_value = formel_params.GW0
messstellen_offset = (idx - len(messstellen_ids) / 2) * 1.02
messwert = basis_value + messstellen_offset
messwert += random.uniform(-formel_params.R_scale * 1.02, formel_params.R_scale * 1.02)
csvwriter.writerow([messstelle_id, formatted_date, f'{messwert:.2f}'.replace('.', ',')])
current_time += hourly_interval
values_created += 1
if values_created % 100 == 0:
if total_values > 0 : progress['value'] = int((values_created / total_values) * 100)
else: progress['value'] = 0
progress_info.config(text=f"Werte generiert ({progress['value']}%)".replace(',', '.'))
root.update_idletasks()
if root.cancel_generation_flag.is_set():
csvfile.close()
return
file_successfully_written = True
created_csv_files_successfully.append(filepath)
except Exception as e:
if not root.cancel_generation_flag.is_set():
print(f"Fehler beim Schreiben der CSV {filepath}: {e}")
finally:
if file_successfully_written and filepath in root.partial_files_to_delete:
root.partial_files_to_delete.remove(filepath)
if root.cancel_generation_flag.is_set(): return
if not root.cancel_generation_flag.is_set() and created_csv_files_successfully:
progress['value'] = 100
abs_output_dir = os.path.abspath(output_directory)
base_name_of_output_dir = os.path.basename(abs_output_dir)
display_folder_name = base_name_of_output_dir
if not display_folder_name:
if len(abs_output_dir) <= 3: display_folder_name = abs_output_dir
else: display_folder_name = "gewählten Ordner"
# Use 'len(messstellen_ids)' for this check
if len(messstellen_ids) == 1:
progress_info.config(text=f"CSV-Datei unter '{display_folder_name}' gespeichert.")
else:
progress_info.config(text=f"CSV-Dateien unter '{display_folder_name}' gespeichert.")
root.update_idletasks()
elif not root.cancel_generation_flag.is_set() and not created_csv_files_successfully:
progress_info.config(text="Fehler: Keine CSV-Dateien erstellt.")
# Ladescreen-Funktion
def show_loading_screen():
global logo_img_global
loading_window = tk.Tk()
loading_window.overrideredirect(True)
window_width = 400
window_height = 300
screen_width = loading_window.winfo_screenwidth()
screen_height = loading_window.winfo_screenheight()
x_pos = int((screen_width/2) - (window_width/2))
y_pos = int((screen_height/2) - (window_height/2))
loading_window.geometry(f"{window_width}x{window_height}+{x_pos}+{y_pos}")
loading_window.configure(bg=DISCORD_DARKER)
try:
logo_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ribeka_Logo.png")
original_logo = Image.open(logo_path)
logo_width = 200
aspect_ratio = original_logo.height / original_logo.width
logo_height = int(logo_width * aspect_ratio)
resized_logo = original_logo.resize((logo_width, logo_height), Image.LANCZOS)
logo_img = ImageTk.PhotoImage(resized_logo)
logo_img_global = logo_img
logo_label = tk.Label(loading_window, image=logo_img, bg=DISCORD_DARKER)
logo_label.image = logo_img
logo_label.pack(pady=(60, 20))
except Exception as e:
print(f"Fehler beim Laden des Logos: {e}")
tk.Label(loading_window, text="WaterGen", font=("Arial", 24, "bold"),
fg=DISCORD_TEXT, bg=DISCORD_DARKER).pack(pady=(60, 20))
loading_label = tk.Label(loading_window, text="Anwendung wird geladen...",
fg=DISCORD_TEXT, bg=DISCORD_DARKER, font=("Arial", 12))
loading_label.pack(pady=10)
progress = ttk.Progressbar(loading_window, orient="horizontal", length=300, mode="indeterminate")
style = ttk.Style(loading_window)
style.configure("TProgressbar", troughcolor=DISCORD_BG, background=DISCORD_GREEN)
progress.pack(pady=20)
progress.start(15)
def close_loading():
progress.stop()
loading_window.destroy()
loading_window.after(2000, close_loading)
loading_window.mainloop()
def resource_path(relative_path):
"""Ermittelt den korrekten Pfad zu Ressourcen für PyInstaller und normale Python-Ausführung"""
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(os.path.dirname(__file__))
return os.path.join(base_path, relative_path)
def create_csv_files_thread_wrapper(root, start_date, end_date, messstellen_ids, interval_hours,
formel_params, progress, progress_info, output_directory,
button_canvas, button_text_item, button_bg_item): # Button Elemente empfangen
try:
create_csv_files(root, start_date, end_date, messstellen_ids, interval_hours,
formel_params, progress, progress_info, output_directory)
if root.cancel_generation_flag.is_set():
progress_info.config(text="Generierung abgebrochen.")
# Cleanup-Logik hier, da der Thread hier die Kontrolle hat
for f_path in root.partial_files_to_delete:
try:
if os.path.exists(f_path):
os.remove(f_path)
print(f"Gelöscht (Abbruch): {f_path}")
except Exception as e_del:
print(f"Fehler beim Löschen (Abbruch) von {f_path}: {e_del}")
root.partial_files_to_delete = [] # Liste leeren
# elif: Kein Fehler und nicht abgebrochen -> Erfolgsmeldung wird von create_csv_files gesetzt.
except Exception as e:
if not root.cancel_generation_flag.is_set(): # Nur Fehler anzeigen, wenn nicht aktiv abgebrochen
progress_info.config(text=f"Fehler im Thread: {str(e)}")
print(f"Thread Error: {e}")
# Cleanup auch bei Fehler (außer es wurde aktiv abgebrochen und dort schon bereinigt)
if not root.cancel_generation_flag.is_set():
for f_path in root.partial_files_to_delete:
try:
if os.path.exists(f_path):
os.remove(f_path)
print(f"Gelöscht (Fehler): {f_path}")
except Exception as e_del:
print(f"Fehler beim Löschen (Fehler) von {f_path}: {e_del}")
root.partial_files_to_delete = []
finally:
# Button immer zurücksetzen, egal ob Erfolg, Fehler oder Abbruch
# Dies muss über root.after geschehen, da es aus einem anderen Thread kommt
def reset_button_ui():
button_canvas.itemconfig(button_text_item, text="Start")
button_canvas.itemconfig(button_bg_item, fill=BUTTON_COLOR) # BUTTON_COLOR verwenden
button_canvas.unbind("<Button-1>") # Eventuell gebundenes cancel_process entfernen
# WICHTIG: Hier muss start_process korrekt referenziert werden.
# Da start_process innerhalb von create_gui definiert ist, muss es entweder
# an diese Funktion übergeben werden oder wir müssen die Lambda-Funktion anpassen,
# um die in create_gui definierte start_process zu verwenden.
# Die aktuelle Übergabe der Button-Elemente ist gut.
# Wir gehen davon aus, dass start_process im Scope von create_gui bekannt ist,
# und das lambda wird zum Zeitpunkt der Ausführung von root.after im korrekten Kontext sein.
button_canvas.bind("<Button-1>", lambda event: root.start_process_method(event)) # Verwende eine Methode von root
if not root.cancel_generation_flag.is_set() and progress['value'] != 100:
if "Fehler" not in progress_info.cget("text") and "Abbruch" not in progress_info.cget("text") and "Warnung" not in progress_info.cget("text"):
progress_info.config(text="Bereit.")
elif progress['value'] == 100 and "Fehler" not in progress_info.cget("text") and not root.cancel_generation_flag.is_set():
pass # Erfolgsmeldung bleibt
elif root.cancel_generation_flag.is_set():
progress_info.config(text="Abgebrochen. Dateien gelöscht.")
progress['value'] = 0
root.after(0, reset_button_ui)
root.generation_thread = None
root.cancel_generation_flag.clear()
# GUI erstellen
def create_gui():
show_loading_screen()
root = tk.Tk()
root.title("WaterGen")
root.generation_thread = None # Zum Speichern des laufenden Threads
root.cancel_generation_flag = threading.Event() # Für sicheres Abbrechen
root.partial_files_to_delete = [] # Liste der Dateien, die bei Abbruch gelöscht werden sollen
logo_path_icon = resource_path("icon.ico") # Korrigierter Variablenname
try:
root.iconbitmap(logo_path_icon) # Korrigierten Variablennamen verwenden
except tk.TclError as e:
print(f"Fehler beim Setzen des Icons (möglicherweise nicht im richtigen Format oder Pfad): {e}")
# Versuche SVG als Fallback, falls tk.Image vorhanden ist (Python 3.9+ mit Tk 8.6+)
try:
svg_icon_path = resource_path("icon.svg") # Annahme: Du hast auch ein SVG Icon
img = tksvg.SvgImage(file=svg_icon_path)
root.iconphoto(True, img)
print("SVG Icon als Fallback verwendet.")
except Exception as svg_e:
print(f"Konnte auch SVG Icon nicht laden: {svg_e}")
except Exception as e: # Fange allgemeinere Fehler ab
print(f"Allgemeiner Fehler beim Setzen des Icons: {e}")
window_width = 620
# window_height = 700 # Alte Höhe
window_height = 780 # NEU: Höhe angepasst für neuen Bereich
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x_pos = int((screen_width/2) - (window_width/2))
y_pos = int((screen_height/2) - (window_height/2))
root.geometry(f"{window_width}x{window_height}+{x_pos}+{y_pos}")
set_dark_title_bar(root)
root.configure(bg=DISCORD_BG)
try:
# Für Windows: Taskleisten-Icon konfigurieren
try:
from ctypes import windll
app_id = "ribeka.watergen.app.1.0"
windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id)
except ImportError:
pass
except Exception as e:
print(f"Fehler beim Setzen der App-ID: {e}")
formel_params = FormelParameter()
# NEU: StringVar für den Ausgabepfad initialisieren
root.output_directory_path = tk.StringVar()
root.output_directory_path.set(os.getcwd()) # Standard: Aktuelles Arbeitsverzeichnis
# root.minsize(620, 720) # Alte Mindestgröße
root.minsize(620, 780) # NEU: Mindesthöhe angepasst
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
container_frame = tk.Frame(root, bg=DISCORD_BG)
container_frame.grid(row=0, column=0, sticky="nsew", padx=10, pady=10)
container_frame.grid_rowconfigure(0, weight=1)
container_frame.grid_columnconfigure(0, weight=1)
content_frame = tk.Frame(container_frame, bg=DISCORD_BG)
def center_content(event=None):
width = container_frame.winfo_width()
if width > 600:
padding = (width - 600) // 2
content_frame.grid_configure(padx=padding)
else:
content_frame.grid_configure(padx=0)
content_frame.grid(row=0, column=0)
container_frame.bind("<Configure>", center_content)
main_frame = tk.Frame(content_frame, bg=DISCORD_BG, padx=15, pady=15)
main_frame.pack(fill=tk.BOTH, expand=True)
style = ttk.Style(root)
style.configure("TProgressbar",
troughcolor=DISCORD_DARKER,
background=BUTTON_COLOR,
borderwidth=0)
label_style = {"bg": DISCORD_DARK, "fg": DISCORD_TEXT, "font": ('Arial', 11)}
entry_style = {"bg": DISCORD_INPUT_BG, "fg": DISCORD_TEXT, "insertbackground": DISCORD_TEXT,
"font": ('Arial', 11), "bd": 0, "relief": "flat"}
header_frame = tk.Frame(main_frame, bg=DISCORD_BG)
header_frame.pack(fill=tk.X, pady=(0, 20))
header_canvas = tk.Canvas(header_frame, bg=DISCORD_BG, height=100,
highlightthickness=0, width=580)
header_canvas.pack(fill=tk.X)
create_rounded_rect(header_canvas, 0, 0, 580, 100, radius=15,
fill=DISCORD_DARK, outline="")
# WaterGen Logo (statisch und animiert)
logo_path_WaterGen_png = resource_path("WaterGen_Logo.png")
logo_path_WaterGen_gif = resource_path("WaterGen_Animation.gif") # Pfad zum GIF
watergen_logo_width = 150
watergen_logo_height = 0
root.static_watergen_logo_tk = None
root.watergen_gif_frames = []
root.watergen_gif_frame_duration = 100
root.is_watergen_animating = False
try:
original_png = Image.open(logo_path_WaterGen_png)
aspect_ratio = original_png.height / original_png.width
watergen_logo_height = int(watergen_logo_width * aspect_ratio)
resized_png = original_png.resize((watergen_logo_width, watergen_logo_height), Image.LANCZOS)
root.static_watergen_logo_tk = ImageTk.PhotoImage(resized_png)
try:
gif_image = Image.open(logo_path_WaterGen_gif)
root.watergen_gif_frame_duration = gif_image.info.get('duration', 100)
for frame in ImageSequence.Iterator(gif_image):
frame_rgba = frame.convert("RGBA")
resized_frame_img = frame_rgba.resize((watergen_logo_width, watergen_logo_height), Image.LANCZOS)
root.watergen_gif_frames.append(ImageTk.PhotoImage(resized_frame_img))
except Exception as e:
print(f"Fehler beim Laden des WaterGen GIF: {e}. Animation nicht verfügbar.")
root.watergen_gif_frames = []
except Exception as e:
print(f"Fehler beim Laden des statischen WaterGen-Logos: {e}")
fallback_label = tk.Label(header_canvas, text="WaterGen",
bg=DISCORD_DARK, fg=DISCORD_TEXT,
font=('Arial', 24, 'bold'))
header_canvas.create_window(120, 50, window=fallback_label)
root.watergen_logo_widget = fallback_label
if root.static_watergen_logo_tk:
watergen_logo_label = tk.Label(header_canvas, image=root.static_watergen_logo_tk, bg=DISCORD_DARK, cursor="hand2")
watergen_logo_label.image = root.static_watergen_logo_tk
root.watergen_logo_widget = watergen_logo_label
header_canvas.create_window(120, 50, window=watergen_logo_label)
def _animate_watergen_gif(frame_index):
if not root.watergen_gif_frames:
root.is_watergen_animating = False
if root.static_watergen_logo_tk:
root.watergen_logo_widget.config(image=root.static_watergen_logo_tk)
root.watergen_logo_widget.image = root.static_watergen_logo_tk
return
if frame_index < len(root.watergen_gif_frames):
frame_image = root.watergen_gif_frames[frame_index]
root.watergen_logo_widget.config(image=frame_image)
root.watergen_logo_widget.image = frame_image
root.after(root.watergen_gif_frame_duration, _animate_watergen_gif, frame_index + 1)
else:
root.watergen_logo_widget.config(image=root.static_watergen_logo_tk)
root.watergen_logo_widget.image = root.static_watergen_logo_tk
root.is_watergen_animating = False
def play_watergen_gif_once(event=None):
if root.is_watergen_animating or not root.watergen_gif_frames:
return
if not hasattr(root, 'watergen_logo_widget') or not root.static_watergen_logo_tk:
return
root.is_watergen_animating = True
_animate_watergen_gif(0)
if hasattr(root, 'watergen_logo_widget'):
root.watergen_logo_widget.bind("<Button-1>", play_watergen_gif_once)
logo_path_ribeka_png = resource_path("ribeka_Logo.png")
logo_path_ribeka_gif = resource_path("ribeka_Animation.gif")
ribeka_logo_width = 200
ribeka_logo_height = 0
root.static_ribeka_logo_tk = None
root.ribeka_gif_frames = []
root.ribeka_gif_frame_duration = 100
root.is_ribeka_animating = False
try:
original_ribeka = Image.open(logo_path_ribeka_png)
aspect_ratio = original_ribeka.height / original_ribeka.width
ribeka_logo_height = int(ribeka_logo_width * aspect_ratio)
resized_ribeka = original_ribeka.resize((ribeka_logo_width, ribeka_logo_height), Image.LANCZOS)
root.static_ribeka_logo_tk = ImageTk.PhotoImage(resized_ribeka)
try:
gif_image = Image.open(logo_path_ribeka_gif)
root.ribeka_gif_frame_duration = gif_image.info.get('duration', 100)
for frame in ImageSequence.Iterator(gif_image):
frame_rgba = frame.convert("RGBA")
resized_frame_img = frame_rgba.resize((ribeka_logo_width, ribeka_logo_height), Image.LANCZOS)
root.ribeka_gif_frames.append(ImageTk.PhotoImage(resized_frame_img))