Repository navigation
Expand file tree
/
Copy pathplot_qvps_interactive.py
More file actions
executable file
·2590 lines (2233 loc) · 103 KB
/
Copy pathplot_qvps_interactive.py
File metadata and controls
executable file
·2590 lines (2233 loc) · 103 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
# -*- coding: utf-8 -*-
"""
plot_qvps_interactive.py
Interactive visualization of Quasi-Vertical Profile (QVP) radar data.
Displays:
- Column 1: 4 stacked 2D QVP heatmaps (Time vs Height) for the day.
Default variables:
Panel 1: DBZH_AC (or DBZH, DBTH, ZH, TH)
Panel 2: ZDR_EC_OC_WRC_AC or ZDR_EC_OC_AC (or ZDR_OC, ZDR, etc.)
Panel 3: KDP_ML_corrected_EC (or KDP_ML_corrected, KDP)
Panel 4: RHOHV_NC (or RHOHV)
Each panel allows selecting any available variable, changing colormaps,
and setting custom vmin/vmax.
Clicking anywhere on any 2D plot selects that specific time profile.
- Column 2: 1D Value vs Height profile for the clicked time.
Automatically displays the 4 variables from Column 1, plus a checkbox list
to add/remove any variable from all available variables.
All variables share the height axis with twin x-axes, each scaled to manageable
ranges, with customizable axis limits, line colors, and line styles.
- Date navigation: Slider and step buttons to move across daily files or dates.
Author: Antigravity / jgiles
"""
import os
os.environ["ICECHUNK_NO_LOGS"] = "1" # Silence Icechunk Rust warnings
import sys
import glob
import re
import argparse
import warnings
from datetime import datetime
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.dates as mdates
import matplotlib.colors as mcolors
from matplotlib.widgets import Slider, Button, CheckButtons, TextBox
from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec
# Icechunk support
try:
from icechunk import Repository, local_filesystem_storage
HAS_ICECHUNK = True
except ImportError:
HAS_ICECHUNK = False
# Possible paths setup (following CFTDs.py convention)
possible_paths = [
'/home/jgiles/Scripts/python/radar_processing_scripts', # Office PC
'/p/scratch/detectrea2/giles1/radar_processing_scripts', # JUWELS Scratch
]
for script_dir in possible_paths:
if os.path.exists(script_dir) and script_dir not in sys.path:
sys.path.insert(0, script_dir)
break
# Attempt imports of local project modules
try:
import utils
except ImportError:
utils = None
try:
import radarmet
except ImportError:
radarmet = None
try:
from scipy.ndimage import binary_opening
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
# Default path pattern following CFTDs.py
DEFAULT_REALPEP_PATH = "/automount/realpep"
DEFAULT_PATH_QVPS = f"{DEFAULT_REALPEP_PATH}/upload/jgiles/dwd/qvps/*/*/2017-07-25/pro/vol5minng01/07/*allmoms*"
DEFAULT_RIMING_DIR = f"{DEFAULT_REALPEP_PATH}/upload/jgiles/radar_riming_classif/unfiltered"
# Common colormap choices
COLORMAP_CHOICES = [
'default (visdict)', 'viridis', 'miub2', 'HomeyerRainbow', 'HomeyerRainbow_disc',
'SpectralExtended', 'plasma', 'inferno', 'magma', 'cividis', 'turbo', 'jet',
'RdBu_r', 'coolwarm', 'binary2'
]
# Distinct palette for 1D profile curves
DEFAULT_PALETTE = [
'#1f77b4', # blue
'#d62728', # red
'#2ca02c', # green
'#9467bd', # purple
'#ff7f0e', # orange
'#17becf', # cyan
'#e377c2', # pink
'#8c564b', # brown
'#bcbd22', # olive
'#333333', # dark gray
'#000080', # navy
'#008080', # teal
]
# Register fallback custom colormaps if missing
colors_prabhakar = np.array([
[0.00, 1.00, 1.00], [0.00, 0.70, 0.93], [0.00, 0.00, 1.00],
[0.50, 1.00, 0.00], [0.40, 0.80, 0.00], [0.27, 0.55, 0.00],
[1.00, 1.00, 0.00], [0.80, 0.80, 0.00], [1.00, 0.65, 0.00],
[1.00, 0.27, 0.00], [0.80, 0.22, 0.00], [0.55, 0.15, 0.00],
[1.00, 0.00, 1.00], [0.58, 0.44, 0.86]
])
try:
if "miub2" not in mpl.colormaps:
mpl.colormaps.register(name="miub2", cmap=mcolors.ListedColormap(colors_prabhakar))
if "binary2" not in mpl.colormaps:
mpl.colormaps.register(name="binary2", cmap=mcolors.ListedColormap(["dimgray", "gainsboro"]))
except Exception:
pass
LINE_STYLES = [
('solid', '-'),
('dashed', '--'),
('dashdot', '-.'),
('dotted', ':')
]
STYLE_MAP = dict(LINE_STYLES)
REV_STYLE_MAP = {v: k for k, v in LINE_STYLES}
def find_files_from_input(paths_input):
"""
Given a string path, list of paths, glob pattern, or directory,
return a sorted list of QVP files matching CFTDs.py conventions or simulation files.
"""
if isinstance(paths_input, str):
paths_input = [paths_input]
files_found = []
for raw_item in paths_input:
if not raw_item:
continue
item = raw_item.strip()
clean_item = item.rstrip('/')
# 1. Glob patterns
if any(c in item for c in ['*', '?', '[']):
matched = glob.glob(item)
files_found.extend([m.rstrip('/') for m in matched])
# 2. Directly specified .zarr store (which is a directory on disk, not a file)
elif clean_item.endswith('.zarr'):
files_found.append(clean_item)
# 3. Directory containing files (and not a .zarr store itself)
elif os.path.isdir(item):
patterns = [
os.path.join(item, "*allsim*"),
os.path.join(item, "*allmoms*"),
os.path.join(item, "*allmom*"),
os.path.join(item, "*allm*"),
os.path.join(item, "*.zarr"),
os.path.join(item, "*.nc"),
os.path.join(item, "*.h5"),
os.path.join(item, "*.hdf5"),
]
dir_matched = []
for pat in patterns:
m = glob.glob(pat)
if m:
dir_matched.extend([x.rstrip('/') for x in m])
if dir_matched:
files_found.extend(dir_matched)
else:
# If no pattern matched inside directory, check all entries
entries = glob.glob(os.path.join(item, "*"))
for entry in entries:
c_entry = entry.rstrip('/')
if c_entry.endswith('.zarr') or c_entry.endswith('.nc') or any(k in c_entry for k in ['allm', 'allsim']):
files_found.append(c_entry)
# 4. Directly specified file
elif os.path.isfile(item):
# If path ends in ML_detected.txt, look for allmoms/allsim in same directory
if os.path.basename(item) == "ML_detected.txt":
m = glob.glob(os.path.join(os.path.dirname(item), "*allm*")) + glob.glob(os.path.join(os.path.dirname(item), "*allsim*"))
if m:
files_found.extend([x.rstrip('/') for x in m])
else:
files_found.append(item)
else:
files_found.append(item)
# 5. Direct fallback: path passed directly (e.g. automount path or file not yet mounted)
else:
files_found.append(clean_item)
# Filter ML_detected.txt if resolved to actual data files
filtered = []
for f in sorted(list(set(files_found))):
c_f = f.rstrip('/')
if os.path.basename(c_f) == "ML_detected.txt":
m = glob.glob(os.path.join(os.path.dirname(c_f), "*allm*")) + glob.glob(os.path.join(os.path.dirname(c_f), "*allsim*"))
if m:
filtered.extend([x.rstrip('/') for x in m])
else:
filtered.append(c_f)
else:
filtered.append(c_f)
# Direct fallback: if still nothing found, use the raw paths provided directly
if not filtered:
for raw_item in paths_input:
if raw_item and raw_item.strip():
filtered.append(raw_item.strip().rstrip('/'))
return sorted(list(set(filtered)))
def extract_date_from_file(file_path):
"""
Extract YYYY-MM-DD string from filename or parent folder path.
"""
# Look for standard YYYY-MM-DD anywhere in the full path
match = re.search(r"(\d{4}-\d{2}-\d{2})", file_path)
if match:
return match.group(1)
# Look for YYYYMMDD in basename
match = re.search(r"(\d{4})(\d{2})(\d{2})", os.path.basename(file_path))
if match:
return f"{match.group(1)}-{match.group(2)}-{match.group(3)}"
# Look for YYYYMMDD anywhere in path
match = re.search(r"(\d{4})(\d{2})(\d{2})", file_path)
if match:
return f"{match.group(1)}-{match.group(2)}-{match.group(3)}"
return None
KNOWN_LOCATIONS = ['pro', 'umd', 'tur', 'afy', 'ank', 'gzt', 'hty', 'svs']
DWD_STATION_IDS = {
'10392': 'pro',
'010392': 'pro',
'10780': 'tur',
'010780': 'tur',
'10629': 'umd',
'010629': 'umd',
}
def extract_radar_location(fpath_or_ds):
"""
Extract 3-letter radar site location (e.g. 'pro', 'gzt', 'hty', 'ank', 'afy', 'svs', 'tur', 'umd')
from a QVP file path, dataset, or filename.
"""
if isinstance(fpath_or_ds, str):
clean = fpath_or_ds.lower()
# Check DWD station IDs
for sid, loc_name in DWD_STATION_IDS.items():
if sid in clean:
return loc_name
# Check path tokens
parts = re.split(r'[/\\_\-]', clean)
for loc in KNOWN_LOCATIONS:
if loc in parts:
return loc
for loc in KNOWN_LOCATIONS:
if re.search(r'[/_\-\.]' + loc + r'[/_\-\.]', clean):
return loc
for loc in KNOWN_LOCATIONS:
if loc in clean:
return loc
if hasattr(fpath_or_ds, 'attrs'):
for attr_k in ['radar', 'radar_id', 'location', 'site', 'station_id']:
if attr_k in fpath_or_ds.attrs:
val = str(fpath_or_ds.attrs[attr_k]).lower()
for sid, loc_name in DWD_STATION_IDS.items():
if sid in val:
return loc_name
for loc in KNOWN_LOCATIONS:
if loc in val:
return loc
return None
def find_riming_file(loc, is_dmi=False, riming_dir=DEFAULT_RIMING_DIR):
"""
Locate the appropriate riming NetCDF file and variable name for a given location and radar network,
matching the decision logic in plot_ppis_qvps_etc.py.
"""
if not loc or not os.path.isdir(riming_dir):
return None, None
if is_dmi or loc in ['afy', 'ank', 'gzt', 'hty', 'svs']:
candidates = [
'riming_ZDR_EC_OC_WRC_AC_DBZH_AC',
'riming_DR_ZDR_EC_OC_WRC_AC_DBZH_AC',
'riming_DR_ZDR_EC_OC_AC_DBZH_AC',
'riming_ZDR_EC_OC_AC_DBZH_AC',
'riming_DR',
'riming_ZDR_DBZH',
'riming_UDR'
]
else:
candidates = [
'riming_DR_ZDR_EC_OC_AC_DBZH_AC',
'riming_ZDR_EC_OC_AC_DBZH_AC',
'riming_DR_ZDR_EC_OC_WRC_AC_DBZH_AC',
'riming_ZDR_EC_OC_WRC_AC_DBZH_AC',
'riming_DR',
'riming_ZDR_DBZH',
'riming_UDR'
]
for c in candidates:
fp = os.path.join(riming_dir, f"{loc}_{c}.nc")
if os.path.exists(fp):
return fp, c
matches = glob.glob(os.path.join(riming_dir, f"{loc}_*.nc"))
if matches:
return matches[0], None
return None, None
class QVPDatasetManager:
"""
Manages loading, caching, date extraction, and dimension alignment for QVP datasets.
Supports:
- Multiple 1-day files (switched via date slider)
- Single file containing 1 or multiple days
- Automatic dimension standardization to 'time' and 'z'
"""
def __init__(self, file_list, min_height=0.0, max_height=12000.0):
self.file_list = sorted(file_list)
self.min_height = min_height
self.max_height = max_height
self.cache = {} # date_str -> xr.Dataset
self.is_single_file_multi_day = False
self.single_file_ds = None
self.date_to_file = {}
self.date_list = []
self._init_date_mapping()
def _open_raw(self, fpath):
"""
Open a QVP data file into memory.
Supports:
1. utils.load_qvps (if available, as done in CFTDs.py)
2. Icechunk zarr repository (via Repository.open and session.store)
3. Standard Zarr store (via xr.open_zarr)
4. NetCDF / HDF5 files (via xr.open_dataset)
"""
clean_path = fpath.rstrip('/')
# 1. Try utils.load_qvps if available (as used in CFTDs.py)
if utils is not None and hasattr(utils, 'load_qvps'):
try:
ds = utils.load_qvps([clean_path], load=True)
if ds is not None:
return ds
except Exception:
pass
# 2. Check for .zarr (could be Icechunk or standard Zarr)
if clean_path.endswith('.zarr'):
# Try Icechunk first (standard storage for DWD/DMI radar QVP processing)
if HAS_ICECHUNK:
try:
storage = local_filesystem_storage(clean_path)
repo = Repository.open(storage)
session = repo.readonly_session("main")
ds = xr.open_zarr(session.store, consolidated=False)
return ds.load()
except Exception:
pass
# Try standard Zarr (consolidated=False, consolidated=True, default)
for cons in [False, True, None]:
try:
if cons is None:
ds = xr.open_zarr(clean_path)
else:
ds = xr.open_zarr(clean_path, consolidated=cons)
return ds.load()
except Exception:
pass
# 3. NetCDF / HDF5 files
for eng in ['h5netcdf', 'netcdf4', None]:
try:
if eng is None:
ds = xr.open_dataset(clean_path)
else:
ds = xr.open_dataset(clean_path, engine=eng)
return ds.load()
except Exception:
pass
# 4. Final attempt with generic open_zarr and open_dataset
try:
return xr.open_zarr(clean_path).load()
except Exception:
pass
return xr.open_dataset(clean_path).load()
def _standardize_ds(self, ds):
# Standardize vertical dimension to 'z'
vert_candidates = ['height', 'range', 'altitude', 'alt', 'height_above_ground', 'height_above_sea_level', 'nheight', 'z_levels', 'level']
for vert_name in vert_candidates:
if 'z' not in ds.dims and vert_name in ds.dims:
ds = ds.rename({vert_name: 'z'})
if 'z' not in ds.coords and vert_name in ds.coords:
ds = ds.assign_coords(z=ds[vert_name])
# Standardize time dimension to 'time'
time_candidates = ['Time', 'datetime', 'valid_time', 'Times', 't']
for t_name in time_candidates:
if 'time' not in ds.dims and t_name in ds.dims:
ds = ds.rename({t_name: 'time'})
if 'time' not in ds.coords and t_name in ds.coords:
ds = ds.assign_coords(time=ds[t_name])
# Drop NaT timestamps if any
if 'time' in ds.coords:
valid_t = ds['time'].notnull().values
if not valid_t.all():
ds = ds.isel(time=valid_t)
return ds
def _init_date_mapping(self):
if not self.file_list:
return
# If only one file, check if it contains multiple dates
if len(self.file_list) == 1:
try:
ds_single = self._open_raw(self.file_list[0])
ds_single = self._standardize_ds(ds_single)
if 'time' in ds_single:
times = pd.to_datetime(ds_single.time.values)
unique_dates = sorted(list(set(str(t.date()) for t in times if pd.notnull(t))))
if len(unique_dates) > 1:
self.is_single_file_multi_day = True
self.single_file_ds = ds_single
self.date_list = unique_dates
return
elif len(unique_dates) == 1:
d_str = unique_dates[0]
self.date_list = [d_str]
self.date_to_file = {d_str: self.file_list[0]}
self.cache[d_str] = ds_single
return
except Exception:
pass
date_to_files = {}
for f in self.file_list:
d_str = extract_date_from_file(f)
if not d_str:
# Open lazily to read time[0]
try:
ds_meta = self._open_raw(f)
if 'time' in ds_meta:
d_str = str(pd.to_datetime(ds_meta.time.values[0]).date())
except Exception:
d_str = os.path.basename(f)
if d_str:
date_to_files.setdefault(d_str, []).append(f)
self.date_list = sorted(date_to_files.keys())
self.date_to_file = {d: date_to_files[d][0] for d in self.date_list}
def load_day(self, date_str):
if date_str in self.cache:
return self.cache[date_str]
if self.is_single_file_multi_day:
ds = self.single_file_ds.sel(time=date_str)
self.cache[date_str] = ds
return ds
fpath = self.date_to_file.get(date_str, None)
if not fpath:
raise ValueError(f"No file found for date {date_str}")
# Load dataset
ds = self._open_raw(fpath)
ds = self._standardize_ds(ds)
# Cache dataset (keep reasonable cache size to save memory)
if len(self.cache) > 8:
self.cache.pop(next(iter(self.cache)))
self.cache[date_str] = ds
return ds
def get_available_variables(self, ds):
"""
Get all 2D data variables that have dimensions ('time', 'z') or ('z', 'time').
"""
valid_vars = []
for v in ds.data_vars:
dims = ds[v].dims
if 'time' in dims and 'z' in dims and (len(dims) == 2 or (len(dims) == 3 and ds[v].size == ds.dims['time'] * ds.dims['z'])):
valid_vars.append(v)
if not valid_vars:
for v in ds.data_vars:
if len(ds[v].dims) == 2:
valid_vars.append(v)
return sorted(valid_vars)
def get_z_coords(self, ds):
for k in ['z', 'height', 'range', 'altitude', 'alt', 'height_above_ground', 'height_above_sea_level']:
if k in ds.coords:
z_vals = ds[k].values
break
else:
if 'z' in ds.dims:
z_vals = np.arange(ds.dims['z'])
else:
z_vals = np.arange(100)
# If z is in kilometers (max < 50), convert to meters
if np.nanmax(z_vals) < 50.0:
z_vals = z_vals * 1000.0
return z_vals
def get_default_variables(self, available_vars):
"""
Picks the 4 default variables specified by the user:
Panel 1: DBZH_AC
Panel 2: ZDR_EC_OC_WRC_AC or ZDR_EC_OC_AC
Panel 3: KDP_ML_corrected_EC
Panel 4: RHOHV_NC
Falls back cleanly to related variables if not present.
"""
p1_candidates = ['DBZH_AC', 'DBZH', 'DBTH_OC', 'DBTH', 'ZH', 'TH']
p2_candidates = [
'ZDR_EC_OC_WRC_AC', 'ZDR_EC_OC_AC', 'ZDR_OC_AC', 'ZDR_AC',
'ZDR_EC_OC_WRC', 'ZDR_EC_OC', 'ZDR_OC', 'ZDR_EC', 'ZDR'
]
p3_candidates = ['KDP_ML_corrected_EC', 'KDP_ML_corrected', 'KDP_CONV', 'KDP']
p4_candidates = ['RHOHV_NC', 'RHOHV', 'URHOHV']
def pick_first(candidates, fallback_idx=0):
for c in candidates:
if c in available_vars:
return c
return available_vars[fallback_idx % len(available_vars)] if available_vars else "DBZH"
v1 = pick_first(p1_candidates, 0)
v2 = pick_first(p2_candidates, 1)
v3 = pick_first(p3_candidates, 2)
v4 = pick_first(p4_candidates, 3)
return [v1, v2, v3, v4]
def get_var_vis_info(var_name, data_array=None):
"""
Resolve colormap, discrete ticks, norm, label, and units from radarmet.visdict14
or intelligent defaults.
"""
vinfo = None
if radarmet is not None and hasattr(radarmet, 'visdict14'):
# Try direct name, then prefix, then radar family
if var_name in radarmet.visdict14:
vinfo = radarmet.visdict14[var_name]
else:
base_prefix = var_name.split("_")[0]
if base_prefix in radarmet.visdict14:
vinfo = radarmet.visdict14[base_prefix]
elif "ZDR" in var_name and "ZDR" in radarmet.visdict14:
vinfo = radarmet.visdict14["ZDR"]
elif "KDP" in var_name and "KDP" in radarmet.visdict14:
vinfo = radarmet.visdict14["KDP"]
elif "RHOHV" in var_name and "RHOHV" in radarmet.visdict14:
vinfo = radarmet.visdict14["RHOHV"]
elif "PHIDP" in var_name and "PHIDP" in radarmet.visdict14:
vinfo = radarmet.visdict14["PHIDP"]
elif ("DBZH" in var_name or "DBTH" in var_name) and "DBZH" in radarmet.visdict14:
vinfo = radarmet.visdict14["DBZH"]
ticks = None
cmap_obj = None
cmap_name = "viridis"
if vinfo is not None:
ticks = vinfo.get("ticks", None)
raw_cmap = vinfo.get("cmap", "viridis")
if isinstance(raw_cmap, str):
cmap_name = raw_cmap
try:
cmap_obj = mpl.colormaps.get_cmap(raw_cmap)
except Exception:
try:
cmap_obj = plt.get_cmap(raw_cmap)
except Exception:
cmap_obj = mpl.colormaps.get_cmap("viridis")
cmap_name = "viridis"
elif isinstance(raw_cmap, mpl.colors.Colormap):
cmap_obj = raw_cmap
cmap_name = getattr(raw_cmap, "name", "custom")
if cmap_obj is None:
cmap_name = "viridis"
cmap_obj = mpl.colormaps.get_cmap("viridis")
# Determine default vmin and vmax
if ticks is not None and len(ticks) > 1:
vmin = float(ticks[0])
vmax = float(ticks[-1])
# Use discrete colormap & norm if utils available
if utils is not None and hasattr(utils, 'get_discrete_cmap'):
try:
cmap_obj = utils.get_discrete_cmap(ticks, cmap_obj)
norm = utils.get_discrete_norm(ticks, cmap_obj)
except Exception:
norm = mpl.colors.BoundaryNorm(ticks, ncolors=len(ticks) - 1, extend='both')
else:
norm = mpl.colors.BoundaryNorm(ticks, ncolors=len(ticks) - 1, extend='both')
else:
# Fallback to dynamic data range
if data_array is not None:
vals = np.asarray(data_array)
valid = vals[np.isfinite(vals)]
if len(valid) > 0:
vmin = float(np.percentile(valid, 2))
vmax = float(np.percentile(valid, 98))
if vmin == vmax:
vmin -= 1.0
vmax += 1.0
else:
vmin, vmax = 0.0, 1.0
else:
vmin, vmax = 0.0, 1.0
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
# Resolve units
units = ""
if data_array is not None and hasattr(data_array, 'attrs'):
units = data_array.attrs.get("units", "")
if not units:
v_upper = var_name.upper()
if any(z in v_upper for z in ["DBZH", "DBTH", "ZH", "TH"]):
units = "dBZ"
elif "ZDR" in v_upper:
units = "dB"
elif "KDP" in v_upper:
units = "°/km"
elif "RHOHV" in v_upper:
units = ""
elif "PHIDP" in v_upper or "UPHIDP" in v_upper or "PHI" in v_upper:
units = "°"
elif "VRADH" in v_upper or "WRADH" in v_upper:
units = "m/s"
elif "LWC" in v_upper or "IWC" in v_upper:
units = "g/m³"
return {
"ticks": ticks,
"cmap": cmap_obj,
"cmap_name": cmap_name,
"norm": norm,
"vmin": vmin,
"vmax": vmax,
"units": units
}
# ==============================================================================
# GUI Implementation using Tkinter + Matplotlib
# ==============================================================================
class QVPInteractiveAppTk:
"""
Modern desktop GUI integrating Matplotlib visualization with Tkinter controls.
"""
def __init__(self, dataset_mgr, initial_date=None):
import tkinter as tk
from tkinter import ttk, messagebox
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
self.tk = tk
self.ttk = ttk
self.messagebox = messagebox
self.FigureCanvasTkAgg = FigureCanvasTkAgg
self.NavigationToolbar2Tk = NavigationToolbar2Tk
self.mgr = dataset_mgr
self.dates = self.mgr.date_list
if not self.dates:
raise ValueError("No valid QVP files/dates found to visualize.")
self.current_date = initial_date if initial_date in self.dates else self.dates[0]
self.current_ds = self.mgr.load_day(self.current_date)
self.all_vars = self.mgr.get_available_variables(self.current_ds)
self.min_height = getattr(self.mgr, 'min_height', 0.0)
self.max_height = getattr(self.mgr, 'max_height', 12000.0)
# Panel settings for Column 1 (4 panels)
defaults = self.mgr.get_default_variables(self.all_vars)
self.col1_settings = []
for i in range(4):
vname = defaults[i]
vis = get_var_vis_info(vname, self.current_ds[vname])
self.col1_settings.append({
'var': vname,
'cmap_name': vis['cmap_name'],
'vmin': vis['vmin'],
'vmax': vis['vmax'],
'vis': vis
})
# Selected 1D profile index and variables for Column 2
self.current_time_idx = 0
self.active_1d_vars = list(defaults) # Start with 4 column 1 variables
self.var_styles = {} # var -> dict(color, linestyle, xmin, xmax)
self._init_var_styles()
# Build UI
self.root = self.tk.Tk()
self.root.title("Interactive QVP Visualizer")
self.root.geometry("1600x950")
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.vlines = []
self.col1_axes = []
self.col1_caxes = []
self.cbars = [None] * 4
self.twin_axes = []
self.show_entropy = True
self.show_riming = True
self.show_ml = True
self.col1_entropy_artists = [None] * 4
self.col1_riming_artists = [None] * 4
self.col1_ml_artists = [None] * 4
self.riming_ds_cache = {}
self.radar_location = None
self._build_widgets()
self.plot_all()
def _init_var_styles(self):
for idx, v in enumerate(self.all_vars):
vis = get_var_vis_info(v, self.current_ds[v])
color = DEFAULT_PALETTE[idx % len(DEFAULT_PALETTE)]
style = LINE_STYLES[(idx // len(DEFAULT_PALETTE)) % len(LINE_STYLES)][1]
self.var_styles[v] = {
'color': color,
'linestyle': style,
'xmin': vis['vmin'],
'xmax': vis['vmax'],
'units': vis['units']
}
def _build_widgets(self):
# Main vertical container
main_frame = self.ttk.Frame(self.root)
main_frame.pack(fill=self.tk.BOTH, expand=True)
# Top Control Bar (Date slider & Step buttons & Height Range)
top_bar = self.ttk.LabelFrame(main_frame, text="Navigation & Settings", padding=(8, 4))
top_bar.pack(side=self.tk.TOP, fill=self.tk.X, padx=6, pady=4)
self.btn_prev_date = self.ttk.Button(top_bar, text="◀ Previous Day", command=self.prev_date)
self.btn_prev_date.pack(side=self.tk.LEFT, padx=4)
self.date_var_label = self.tk.StringVar(value=f"Date: {self.current_date} (1 of {len(self.dates)})")
lbl_date = self.ttk.Label(top_bar, textvariable=self.date_var_label, font=("Helvetica", 10, "bold"), width=30)
lbl_date.pack(side=self.tk.LEFT, padx=6)
self.date_scale_val = self.tk.DoubleVar(value=self.dates.index(self.current_date))
self.date_scale = self.ttk.Scale(
top_bar, from_=0, to=max(1, len(self.dates) - 1),
orient=self.tk.HORIZONTAL, variable=self.date_scale_val,
command=self.on_date_slider_move
)
self.date_scale.pack(side=self.tk.LEFT, fill=self.tk.X, expand=True, padx=8)
self.btn_next_date = self.ttk.Button(top_bar, text="Next Day ▶", command=self.next_date)
self.btn_next_date.pack(side=self.tk.LEFT, padx=4)
if len(self.dates) <= 1:
self.date_scale.configure(state="disabled")
self.btn_prev_date.configure(state="disabled")
self.btn_next_date.configure(state="disabled")
# Height range controls directly on top bar
h_bar = self.ttk.Frame(top_bar)
h_bar.pack(side=self.tk.RIGHT, padx=6)
self.ttk.Label(h_bar, text="Height [m]:", font=("Helvetica", 9, "bold")).pack(side=self.tk.LEFT, padx=(6, 2))
self.ent_min_h = self.ttk.Entry(h_bar, width=6)
self.ent_min_h.insert(0, f"{self.min_height:.0f}")
self.ent_min_h.pack(side=self.tk.LEFT, padx=2)
self.ttk.Label(h_bar, text="to").pack(side=self.tk.LEFT, padx=2)
self.ent_max_h = self.ttk.Entry(h_bar, width=6)
self.ent_max_h.insert(0, f"{self.max_height:.0f}")
self.ent_max_h.pack(side=self.tk.LEFT, padx=2)
self.btn_apply_h = self.ttk.Button(h_bar, text="Apply", command=self.apply_height_range)
self.btn_apply_h.pack(side=self.tk.LEFT, padx=4)
self.btn_entropy = self.ttk.Button(h_bar, text="Entropy: ON", command=self.toggle_entropy)
self.btn_entropy.pack(side=self.tk.LEFT, padx=3)
self.btn_riming = self.ttk.Button(h_bar, text="Riming: ON", command=self.toggle_riming)
self.btn_riming.pack(side=self.tk.LEFT, padx=3)
self.btn_ml = self.ttk.Button(h_bar, text="ML: ON", command=self.toggle_ml)
self.btn_ml.pack(side=self.tk.LEFT, padx=3)
self.ent_min_h.bind("<Return>", lambda e: self.apply_height_range())
self.ent_max_h.bind("<Return>", lambda e: self.apply_height_range())
# Content Frame: Split between Matplotlib Canvas (Left) and Sidebar Notebook (Right)
content_frame = self.ttk.Frame(main_frame)
content_frame.pack(side=self.tk.TOP, fill=self.tk.BOTH, expand=True)
# Right-side notebook for controls
self.sidebar = self.ttk.Notebook(content_frame, width=420)
self.sidebar.pack(side=self.tk.RIGHT, fill=self.tk.Y, padx=4, pady=4)
# Matplotlib Area (Left)
plot_frame = self.ttk.Frame(content_frame)
plot_frame.pack(side=self.tk.LEFT, fill=self.tk.BOTH, expand=True)
# Create Matplotlib Figure
self.fig = mpl.figure.Figure(figsize=(12, 9), dpi=100)
self.fig.patch.set_facecolor('#ffffff')
# Main GridSpec: 1 row, 2 columns (Left: 2D panels + dedicated colorbars, Right: 1D profile)
self.gs_main = self.fig.add_gridspec(
1, 2,
width_ratios=[1.5, 1.0],
left=0.07, right=0.96,
bottom=0.08, top=0.95,
wspace=0.28
)
# Left Column: 4 rows x 2 cols (Heatmap, dedicated Colorbar)
self.gs_left = GridSpecFromSubplotSpec(
4, 2,
subplot_spec=self.gs_main[0, 0],
width_ratios=[1.0, 0.035],
wspace=0.04,
hspace=0.24
)
self.col1_axes = []
self.col1_caxes = [None] * 4
for i in range(4):
ax = self.fig.add_subplot(self.gs_left[i, 0], sharex=self.col1_axes[0] if i > 0 else None)
self.col1_axes.append(ax)
# Right Column: 1D QVP profile
self.gs_right = GridSpecFromSubplotSpec(
1, 1,
subplot_spec=self.gs_main[0, 1]
)
orig_bbox = self.gs_right[0, 0].get_position(self.fig)
self.ax_prof = self.fig.add_axes(orig_bbox)
# Canvas & Toolbar
self.canvas = self.FigureCanvasTkAgg(self.fig, master=plot_frame)
self.canvas_widget = self.canvas.get_tk_widget()
self.canvas_widget.pack(side=self.tk.TOP, fill=self.tk.BOTH, expand=True)
self.toolbar = self.NavigationToolbar2Tk(self.canvas, plot_frame)
self.toolbar.update()
# Connect click & resize events
self.canvas.mpl_connect('button_press_event', self.on_canvas_click)
self.canvas.mpl_connect('resize_event', lambda e: self.update_column2_profile())
# Build Sidebar Tabs
self._build_sidebar_tab1_panels()
self._build_sidebar_tab2_variables()
self._build_sidebar_tab3_styles()
def _build_sidebar_tab1_panels(self):
tab = self.ttk.Frame(self.sidebar, padding=6)
self.sidebar.add(tab, text="2D QVP Panels (1-4)")
# Scrollable container for panel configs
c = self.tk.Canvas(tab, borderwidth=0, highlightthickness=0)
sb = self.ttk.Scrollbar(tab, orient=self.tk.VERTICAL, command=c.yview)
subframe = self.ttk.Frame(c)
subframe.bind("<Configure>", lambda e: c.configure(scrollregion=c.bbox("all")))
c.create_window((0, 0), window=subframe, anchor="nw")
c.configure(yscrollcommand=sb.set)
c.pack(side=self.tk.LEFT, fill=self.tk.BOTH, expand=True)
sb.pack(side=self.tk.RIGHT, fill=self.tk.Y)
self.panel_ui_elements = []
# Global Height Range Card
card_h = self.ttk.LabelFrame(subframe, text="Height Range (y-axis)", padding=6)
card_h.pack(fill=self.tk.X, expand=True, pady=4, padx=2)
row_h1 = self.ttk.Frame(card_h)
row_h1.pack(fill=self.tk.X, pady=2)
self.ttk.Label(row_h1, text="Min (m):", width=8).pack(side=self.tk.LEFT)
self.ent_min_tab1 = self.ttk.Entry(row_h1, width=8)
self.ent_min_tab1.insert(0, f"{self.min_height:.0f}")
self.ent_min_tab1.pack(side=self.tk.LEFT, padx=2)
self.ttk.Label(row_h1, text="Max (m):", width=8).pack(side=self.tk.LEFT, padx=(6, 0))
self.ent_max_tab1 = self.ttk.Entry(row_h1, width=8)
self.ent_max_tab1.insert(0, f"{self.max_height:.0f}")
self.ent_max_tab1.pack(side=self.tk.LEFT, padx=2)
row_h2 = self.ttk.Frame(card_h)
row_h2.pack(fill=self.tk.X, pady=(4, 2))
btn_apply_h_tab = self.ttk.Button(
row_h2, text="Apply Range",
command=lambda: self.apply_height_range(
float(self.ent_min_tab1.get()), float(self.ent_max_tab1.get())
)
)
btn_apply_h_tab.pack(side=self.tk.LEFT, padx=2)
btn_reset_h = self.ttk.Button(
row_h2, text="Reset (0 - 12000m)",
command=lambda: self.apply_height_range(0.0, 12000.0)
)
btn_reset_h.pack(side=self.tk.LEFT, padx=4)
row_h3 = self.ttk.Frame(card_h)
row_h3.pack(fill=self.tk.X, pady=(4, 2))
self.btn_entropy_tab = self.ttk.Button(row_h3, text="Entropy: ON", command=self.toggle_entropy)
self.btn_entropy_tab.pack(side=self.tk.LEFT, padx=2)
self.btn_riming_tab = self.ttk.Button(row_h3, text="Riming: ON", command=self.toggle_riming)
self.btn_riming_tab.pack(side=self.tk.LEFT, padx=2)
self.btn_ml_tab = self.ttk.Button(row_h3, text="ML: ON", command=self.toggle_ml)
self.btn_ml_tab.pack(side=self.tk.LEFT, padx=2)
for i in range(4):
card = self.ttk.LabelFrame(subframe, text=f"Panel {i+1} Settings (Row {i+1})", padding=6)
card.pack(fill=self.tk.X, expand=True, pady=4, padx=2)
# Variable selection
row1 = self.ttk.Frame(card)
row1.pack(fill=self.tk.X, pady=2)
self.ttk.Label(row1, text="Variable:", width=10).pack(side=self.tk.LEFT)
cb_var = self.ttk.Combobox(row1, values=self.all_vars, state="normal")
cb_var.set(self.col1_settings[i]['var'])
cb_var.pack(side=self.tk.LEFT, fill=self.tk.X, expand=True)
# Colormap
row2 = self.ttk.Frame(card)
row2.pack(fill=self.tk.X, pady=2)
self.ttk.Label(row2, text="Colormap:", width=10).pack(side=self.tk.LEFT)
cb_cmap = self.ttk.Combobox(row2, values=COLORMAP_CHOICES, state="readonly")
cb_cmap.set(self.col1_settings[i]['cmap_name'])
cb_cmap.pack(side=self.tk.LEFT, fill=self.tk.X, expand=True)
# Vmin and Vmax
row3 = self.ttk.Frame(card)
row3.pack(fill=self.tk.X, pady=2)
self.ttk.Label(row3, text="vmin:", width=6).pack(side=self.tk.LEFT)
ent_vmin = self.ttk.Entry(row3, width=8)
ent_vmin.insert(0, f"{self.col1_settings[i]['vmin']:.2f}")
ent_vmin.pack(side=self.tk.LEFT, padx=2)
self.ttk.Label(row3, text="vmax:", width=6).pack(side=self.tk.LEFT, padx=(6, 0))
ent_vmax = self.ttk.Entry(row3, width=8)
ent_vmax.insert(0, f"{self.col1_settings[i]['vmax']:.2f}")
ent_vmax.pack(side=self.tk.LEFT, padx=2)
# Buttons row
row4 = self.ttk.Frame(card)
row4.pack(fill=self.tk.X, pady=(4, 2))
btn_apply = self.ttk.Button(row4, text="Apply", command=lambda p=i: self.apply_panel_settings(p))
btn_apply.pack(side=self.tk.LEFT, padx=2)
btn_reset = self.ttk.Button(row4, text="Reset Defaults", command=lambda p=i: self.reset_panel_defaults(p))
btn_reset.pack(side=self.tk.LEFT, padx=4)
self.panel_ui_elements.append({
'var': cb_var,
'cmap': cb_cmap,
'vmin': ent_vmin,
'vmax': ent_vmax
})
def _build_sidebar_tab2_variables(self):
tab = self.ttk.Frame(self.sidebar, padding=6)
self.sidebar.add(tab, text="1D Variables (Checkboxes)")
top_row = self.ttk.Frame(tab)
top_row.pack(fill=self.tk.X, pady=2)
self.ttk.Label(top_row, text="Filter:").pack(side=self.tk.LEFT)
self.filter_var = self.tk.StringVar()
self.filter_var.trace_add("write", lambda *_: self._filter_variable_checkboxes())
ent_filter = self.ttk.Entry(top_row, textvariable=self.filter_var)