Repository navigation
Expand file tree
/
Copy pathCFTDs.py
More file actions
5813 lines (4820 loc) · 297 KB
/
Copy pathCFTDs.py
File metadata and controls
5813 lines (4820 loc) · 297 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 -*-
"""
Created on Wed Aug 9 09:53:58 2023
@author: jgiles
Script for calculating CFTDS
"""
import os
os.environ["ICECHUNK_NO_LOGS"] = "1" # Silence Icechunk Rust warnings
import sys
# List all possible paths where this script might live
possible_paths = [
'/home/jgiles/Scripts/python/radar_processing_scripts', # Office PC
'/p/scratch/detectrea2/giles1/radar_processing_scripts', # JUWELS Scratch
]
# Find the one that exists on the current machine and add it
for script_dir in possible_paths:
if os.path.exists(script_dir):
if script_dir not in sys.path:
sys.path.insert(0, script_dir)
break # Stop checking once we find the right one
import wradlib as wrl
import numpy as np
import glob
import xarray as xr
import datetime as dt
import pandas as pd
import datetime
from dask.diagnostics import ProgressBar
from xhistogram.xarray import histogram
import matplotlib.pyplot as plt
import matplotlib as mpl
import xradar as xd
import time
import ridgeplot
import seaborn as sns
import plotly
import pickle
import scipy
import dask
import shutil
from joblib import Parallel, delayed
from itertools import combinations_with_replacement
# Icechunk helper functions
from icechunk import Repository, local_filesystem_storage
from icechunk.xarray import to_icechunk
def save_icechunk(ds, path, append=False):
"""Helper to save or append xarray dataset to Icechunk repository."""
import os
import shutil
if append:
storage = local_filesystem_storage(path)
repo = Repository.open(storage)
session = repo.writable_session("main")
to_icechunk(ds, session, append_dim="time", align_chunks=True)
session.commit("Append data")
else:
# If writing fresh (not appending), remove any existing/corrupted folder
if os.path.exists(path):
shutil.rmtree(path, ignore_errors=True)
storage = local_filesystem_storage(path)
repo = Repository.create(storage)
session = repo.writable_session("main")
to_icechunk(ds, session, mode="w", align_chunks=True)
session.commit("Save data")
def open_icechunk(path):
"""Helper to load xarray dataset from Icechunk repository."""
storage = local_filesystem_storage(path)
repo = Repository.open(storage)
session = repo.readonly_session("main")
return xr.open_zarr(session.store, consolidated=False)
import utils
import radarmet
import warnings
warnings.filterwarnings('ignore', category=RuntimeWarning)
warnings.simplefilter('ignore', np.exceptions.RankWarning)
warnings.filterwarnings("ignore", message="Polyfit may be poorly conditioned")
# Ugly fix to supress polyfit warnings
import xarray.core.nputils as nputils
nputils.warn_on_deficient_rank = lambda *args, **kwargs: None
# we define a funtion to look for loc inside a path string
def find_loc(locs, path):
components = path.split(os.path.sep)
for element in locs:
for component in components:
if element.lower() in component.lower():
return element
return None
locs = ["boxpol", "pro", "tur", "umd", "afy", "ank", "gzt", "hty", "svs"]
realpep_path = "/automount/realpep/"
suffix_name = "" # suffix to add to folder names, for special cases (like computing only a selection of cases)
print("!!!! Future proofing: maybe adding guard is needed for multiprocessing !!!!")
#if __name__ == "__main__": # set guard
#%% Load QVPs for stratiform-case CFTDs
calculate_retrievals = True # Calculate retrievals based on the QVPs?
reload_zarr = False # reload directly qvp single-file from zarr archive?
# This part should be run after having the QVPs computed (compute_qvps.py)
start_time = time.time()
print("Loading QVPs...")
#### Get QVP file list
path_qvps = realpep_path+"/upload/jgiles/dwd/qvps/*/*/*/pro/vol5minng01/07/*allmoms*"
path_qvps = realpep_path+"/upload/jgiles/dwd/qvps_singlefile/ML_detected/pro/vol5minng01/07/*allmoms*"
# Load only events with ML detected (pre-condition for stratiform)
path_qvps = realpep_path+"/upload/jgiles/dwd/qvps/20*/*/*/pro/vol5minng01/07/ML_detected.txt"
path_qvps = realpep_path+"/upload/jgiles/dwd/qvps"+suffix_name+"/20*/*/*/pro/vol5minng01/07/ML_detected.txt"
# path_qvps = realpep_path+"/upload/jgiles/dmi/qvps/20*/*/*/HTY/*/*/ML_detected.txt"
# path_qvps = realpep_path+"/upload/jgiles/boxpol/qvps/20*/*/2017-07-25/n_ppi_110deg/ML_detected.txt"
# path_qvps = realpep_path+"/upload/jgiles/dwd/qvps_singlefile/ML_detected/pro/vol5minng01/07/*allmoms*"
# path_qvps = realpep_path+"/upload/jgiles/dmi/qvps/*/*/*/SVS/*/*/ML_detected.txt"
# path_qvps = realpep_path+"/upload/jgiles/dmi/qvps_singlefile/ML_detected/ANK/*/12*/*allmoms*"
# path_qvps = realpep_path+"/upload/jgiles/dmi/qvps_monthly/*/*/ANK/*/12*/*allmoms*"
# path_qvps = [realpep_path+"/upload/jgiles/dmi/qvps_monthly/*/*/ANK/*/12*/*allmoms*",
# realpep_path+"/upload/jgiles/dmi/qvps_monthly/*/*/ANK/*/14*/*allmoms*"]
#!!! IMPORTANT !!!!
# Date 2020-10-19 for AFY at 7.0 elevation has some issue that triggers an error in the ZDR_EC_OC_AC variable
# IndexError: index 255 is out of bounds for axis 0 with size 240
# ValueError: Array chunk size or shape is unknown. Possible solution with x.compute_chunk_sizes()
# Remove it (I leave this here for future reference)
#### Set variable names
X_DBZH = "DBZH_AC"
X_RHO = "RHOHV_NC" # if RHOHV_NC is set here, it is then checked against the original RHOHV in the next cell
X_ZDR = "ZDR_EC_OC_AC"
X_KDP = "KDP_ML_corrected_EC"
X_PHI = "UPHIDP_UF_OC_MASKED"
if "dwd" in path_qvps:
country="dwd"
X_TH = "TH"
if "boxpol" in path_qvps:
country="boxpol"
X_TH = "DBTH"
X_PHI = "PHIDP_UF_OC_MASKED"
elif "dmi" in path_qvps:
country="dmi"
X_TH = "DBZH"
X_PHI = "PHIDP_UF_OC_MASKED"
X_ZDR = "ZDR_EC_OC_WRC_AC"
ff_glob = glob.glob(path_qvps)
if "dmi" in path_qvps:
# create a function to only select the elevation closer to 10 for each date
from collections import defaultdict
def get_closest_elevation(paths):
elevation_dict = defaultdict(list)
for path in paths:
parts = path.split('/')
date = parts[-5]
elevation = float(parts[-2])
elevation_dict[date].append((elevation, path))
result_paths = []
for date, elevations in elevation_dict.items():
closest_elevation_path = min(elevations, key=lambda x: abs(x[0] - 10.1))[1] # We use 10.1 to prefer elevation 12 instead of 8 if both available
result_paths.append(closest_elevation_path)
return result_paths
ff_glob = get_closest_elevation(ff_glob)
try:
ff = [glob.glob(os.path.dirname(fp)+"/*allm*")[0] for fp in ff_glob ]
except IndexError:
ff = [glob.glob(os.path.dirname(fp)+"/*12345*")[0] for fp in ff_glob ]
path_qvpsinglefile = path_qvps.split("qvps"+suffix_name+"/")[0]+"qvps_singlefile"+suffix_name+"/ML_detected/"+utils.find_loc(locs,path_qvps)+"/qvps.zarr"
if not reload_zarr:
if "HTY" in path_qvps:
variables = utils.selected_variables['hty']
else: variables=None
qvps = utils.load_qvps(ff, load=True, fix_TEMP=False, fillna=False, variables=variables)
# Move TEMP to coordinate
if "TEMP" not in qvps.coords:
qvps = qvps.set_coords("TEMP")
files_to_load = sorted(glob.glob(ff)) if isinstance(ff, str) else sorted(ff)
is_zarr_input = all(f.endswith('.zarr') or f.endswith('.zarr/') for f in files_to_load)
if not is_zarr_input:
# Save QVPs into single file and reload
print("Saving QVPs in single zarr file and reloading...")
# BULLETPROOF OVERWRITE: Remove the old directory if it exists
if os.path.exists(path_qvpsinglefile):
print(f"...Removing old archive at {path_qvpsinglefile}...")
shutil.rmtree(path_qvpsinglefile)
os.makedirs(os.path.dirname(path_qvpsinglefile), exist_ok=True)
if "HTY" in path_qvps:
# For hty we split the process into years because it is too large
unique_years = np.unique(qvps['time'].dt.year.values)
# Loop through each year and save/append to Zarr
for i, year in enumerate(unique_years):
print(f"... year {year} ...")
# Isolate the data for just this year
qvps_year = qvps.sel(time=qvps['time'].dt.year == year)
# Apply your uniform chunk sizes to fix the Zarr shape requirements
qvps_year = qvps_year.chunk({'time': 200, 'z': 200})
# Save or Append
if i == 0:
# First year: initialize the Zarr store
save_icechunk(qvps_year, path_qvpsinglefile, append=False)
else:
# Subsequent years: append along the time dimension
save_icechunk(qvps_year, path_qvpsinglefile, append=True)
else:
save_icechunk(qvps.chunk({'time': 200, 'z': 200}), path_qvpsinglefile, append=False)
qvps = open_icechunk(path_qvpsinglefile)
else:
print("Input files are already Zarr, skipping unified archive creation...")
else:
qvps = open_icechunk(path_qvpsinglefile)
# # Load daily data
# # ## Special selection of convective dates based on DBZH_over_30.txt files
# special_selection = realpep_path+"/upload/jgiles/dwd/qvps/*/*/*/pro/vol5minng01/07/DBZH_over_30*"
# special_filter = realpep_path+"/upload/jgiles/dwd/qvps/*/*/*/pro/vol5minng01/07/ML_detected_*"
# path_special = glob.glob(special_selection)
# path_filter = glob.glob(special_filter)
# path_filter_dirs = [os.path.dirname(ff) for ff in path_filter]
# path_daily = []
# for ff in path_special:
# if os.path.dirname(ff) in path_filter_dirs:
# continue
# path_daily.append(os.path.dirname("/".join(ff.split("/qvps/")))+"/*allmoms*")
# if isinstance(path_daily, str):
# files_daily = sorted(glob.glob(path_daily))
# elif len(path_daily)==1:
# files_daily = sorted(glob.glob(path_daily[0]))
# else:
# files_daily = []
# for fglob in path_daily:
# files_daily.extend(glob.glob(fglob))
# def fix_dailys(data):
# # fix time dim in case some value is NaT
# if data.time.isnull().any():
# data.coords["time"] = data["rtime"].min(dim="azimuth", skipna=True).compute()
# # take time out of the coords if necessary
# for coord in ["latitude", "longitude", "altitude", "elevation"]:
# if "time" in data[coord].dims:
# data.coords[coord] = data.coords[coord].min("time")
# for X_PHI in ["PHIDP"]:
# if X_PHI in data.data_vars:
# # flip PHIDP in case it is wrapping around the edges (case for turkish radars)
# if data[X_PHI].notnull().any():
# values_center = ((data[X_PHI]>-50)*(data[X_PHI]<50)).sum().compute()
# values_sides = ((data[X_PHI]>50)+(data[X_PHI]<-50)).sum().compute()
# if values_sides > values_center:
# data[X_PHI] = xr.where(data[X_PHI]<=0, data[X_PHI]+180, data[X_PHI]-180, keep_attrs=True).compute()
# return data
# open_files=[]
# for ff in files_daily[0:20]:
# if "dwd" in ff:
# # basepath=ff.split("dwd")
# open_files.append(fix_dailys(xr.open_datatree(ff)["sweep_"+ff.split("/")[-2][1]].to_dataset()))
# else:
# open_files.append(fix_dailys(xr.open_dataset(ff)))
# data = xr.concat(open_files, dim="time")
total_time = time.time() - start_time
print(f"took {total_time/60:.2f} minutes.")
#%% Process QVPs
# Conditions to clean ML height values
max_change = 400 # set a maximum value of ML height change from one timestep to another (in m)
max_std = 200 # set a maximum value of ML std from one timestep to another (in m)
time_window = 5 # set timestep window for the std computation (centered)
min_period = 3 # set minimum number of valid ML values in the window (centered)
# min value for SNRH thresholding. This has a significant influence in the KDP calculation and also affects the QVPs computations.
# Here is just redundant but I add it anyways
SNRH_min = 15
min_entropy_thresh = 0.85
# Filter only stratiform events (min entropy >= min_entropy_thresh) and ML detected
# with ProgressBar():
# qvps_strat = qvps.where( (qvps["min_entropy"]>=min_entropy_thresh) & (qvps.height_ml_bottom_new_gia.notnull()), drop=True).compute()
riming_varnames =['riming_DR_'+"_".join([X_ZDR, X_DBZH]),
'riming_'+"_".join([X_ZDR, X_DBZH]),
]
start_time = time.time()
print("Processing QVPs...")
loc = find_loc(locs, ff[0])
#### RHOHV noise correction verification
# Check that RHOHV_NC is actually better (less std) than RHOHV, otherwise just use RHOHV, on a per-day basis
std_tolerance = 0.15 # std(RHOHV_NC) must be < (std(RHOHV))*(1+std_tolerance), otherwise use RHOHV
min_rho = 0.7 # min RHOHV value for filtering. Only do this test with the highest values to avoid wrong results
mean_tolerance = 0.02 # 2% tolerance, for checking if RHOHV_NC is actually larger than RHOHV (overall higher values)
if "_NC" in X_RHO:
# Check that the corrected RHOHV does not have higher STD than the original (1 + std_tolerance)
# if that is the case we take it that the correction did not work well so we won't use it
cond_rhohv1 = (
qvps[X_RHO].where(qvps[X_RHO]>min_rho).resample({"time":"D"}).std(dim=("time", "z")) < \
qvps["RHOHV"].where(qvps["RHOHV"]>min_rho).resample({"time":"D"}).std(dim=("time", "z"))*(1+std_tolerance)
).compute()
# Check that the corrected RHOHV have overall higher mean than the original (1 - mean_tolerance)
# if that is the case we take it that the correction did not work well so we won't use it
cond_rhohv2 = ( qvps[X_RHO].resample({"time":"D"}).mean(dim=("time", "z")) > \
qvps["RHOHV"].resample({"time":"D"}).mean(dim=("time", "z"))*(1-mean_tolerance) ).compute()
cond_rhohv = cond_rhohv1 * cond_rhohv2
# create an xarray.Dataarray with the valid timesteps
valid_dates = cond_rhohv.where(cond_rhohv, drop=True).time.dt.date
valid_datetimes = [date.values in valid_dates for date in qvps.time.dt.date]
valid_datetimes_xr = xr.DataArray(valid_datetimes, coords={"time": qvps["time"]})
# Redefine RHOHV_NC: keep it in the valid datetimes, put RHOHV in the rest
qvps[X_RHO] = qvps[X_RHO].where(valid_datetimes_xr, qvps["RHOHV"])
#### Calculate retrievals
p_time = time.time()
print("Calculating and/or extracting microphysical retrievals...")
# We do this for both qvps_strat_fil and relaxed qvps_strat_relaxed_fil
# to check the wavelength of each radar, in cm for DWD, in 1/100 cm for DMI ()
# filewl = ""
# xr.open_dataset(filewl, group="how") # DWD
# file1 = realpep_path+"/upload/jgiles/dmi_raw/acq/OLDDATA/uza/RADAR/2015/01/01/ANK/RAW/ANK150101000008.RAW6M00"
# xd.io.backends.iris.IrisRawFile(file1, loaddata=False).ingest_header["task_configuration"]["task_misc_info"]["wavelength"]
Lambda = 53.1 # radar wavelength in mm (pro: 53.138, ANK: 53.1, AFY: 53.3, GZT: 53.3, HTY: 53.3, SVS:53.3)
if country == "boxpol":
Lambda = 32
# We will put the final retrievals in a dict
try: # check if exists, if not, create it
retrievals_qvpbased
except NameError:
retrievals_qvpbased = {}
# Calculate only for unfiltered QVPs, then we will filter them later
for stratname, stratqvp in [("unfiltered", qvps.copy()),
]:
# print(" ... for "+stratname)
retrievals_qvpbased[stratname] = {}
if calculate_retrievals:
retrievals_qvpbased[stratname][loc] = utils.calc_microphys_retrievals(stratqvp, Lambda = Lambda, mu=0.33,
X_DBZH=X_DBZH, X_ZDR=X_ZDR, X_KDP=X_KDP, X_TEMP="TEMP",
X_PHI=X_PHI )
# Save retrievals
if not os.path.exists(realpep_path+"/upload/jgiles/radar_retrievals_QVPbased"+suffix_name+"/"+stratname):
os.makedirs(realpep_path+"/upload/jgiles/radar_retrievals_QVPbased"+suffix_name+"/"+stratname)
for ll in retrievals_qvpbased[stratname].keys():
# with dask.config.set(scheduler='single-threaded'):
# retrievals_qvpbased[stratname][ll].to_netcdf(realpep_path+"/upload/jgiles/radar_retrievals_QVPbased"+suffix_name+"/"+stratname+"/"+ll+".nc", engine='h5netcdf')
save_icechunk(retrievals_qvpbased[stratname][ll].chunk({'time':200, 'z': -1}), realpep_path+"/upload/jgiles/radar_retrievals_QVPbased"+suffix_name+"/"+stratname+"/"+ll+".zarr", append=False)
retrievals_qvpbased[stratname][ll] = open_icechunk(realpep_path+"/upload/jgiles/radar_retrievals_QVPbased"+suffix_name+"/"+stratname+"/"+ll+".zarr")
# Check also if the retrievals are already in the QVP and pull them into a new dict
try: # check if exists, if not, create it
retrievals
except NameError:
retrievals = {}
for stratname, stratqvp in [("unfiltered", qvps.copy()),
]:
retrievals_namelist = [
"lwc_zh_zdr_reimann2021",
"lwc_zh_zdr_rhyzkov2022",
"lwc_kdp_reimann2021",
"lwc_ah_reimann2021",
"lwc_hybrid_reimann2021",
"iwc_zh_t_hogan2006",
"iwc_zh_t_hogan2006_model",
"iwc_zh_t_hogan2006_combined",
"iwc_zdr_zh_kdp_carlin2021",
"Dm_ice_zh_matrosov2019",
"Dm_ice_zh_kdp_carlin2021",
"Dm_ice_zdp_kdp_carlin2021",
"Dm_hybrid_blanke2023",
"Dm_rain_zdr_chen",
"Dm_rain_zdr_hu2022",
"Dm_rain_zdr_bringi2009",
"Nt_ice_iwc_zh_t_hu2022",
"Nt_ice_iwc_zh_t_carlin2021",
"Nt_ice_iwc_zh_t_combined_hu2022",
"Nt_ice_iwc_zh_t_combined_carlin2021",
"Nt_ice_iwc_zdr_zh_kdp_hu2022",
"Nt_ice_iwc_zdr_zh_kdp_carlin2021",
"Nt_rain_zh_zdr_rhyzkov2020",
]
retrievals[stratname] = {}
if calculate_retrievals:
# Save retrievals
retrievals[stratname][loc] = xr.Dataset({key: stratqvp[key] for key in retrievals_namelist if key in stratqvp.data_vars})
if not os.path.exists(realpep_path+"/upload/jgiles/radar_retrievals"+suffix_name+"/"+stratname):
os.makedirs(realpep_path+"/upload/jgiles/radar_retrievals"+suffix_name+"/"+stratname)
for ll in retrievals[stratname].keys():
# with dask.config.set(scheduler='single-threaded'):
# retrievals[stratname][ll].to_netcdf(realpep_path+"/upload/jgiles/radar_retrievals"+suffix_name+"/"+stratname+"/"+ll+".nc", engine='h5netcdf')
save_icechunk(retrievals[stratname][ll].chunk({'time':200, 'z': -1}), realpep_path+"/upload/jgiles/radar_retrievals"+suffix_name+"/"+stratname+"/"+ll+".zarr", append=False)
# reload
retrievals[stratname][ll] = open_icechunk(realpep_path+"/upload/jgiles/radar_retrievals"+suffix_name+"/"+stratname+"/"+ll+".zarr")
partial_time = time.time() - p_time
print(f"... took {partial_time/60:.2f} minutes.")
#### Load riming
# We do this for both qvps_strat_fil and relaxed qvps_strat_relaxed_fil
print("Loading riming ...")
p_time = time.time()
# We will put the final riming classification in a dict
try: # check if exists, if not, create it
riming_classif
except NameError:
riming_classif = {}
for stratname in ["unfiltered"]:
if stratname not in riming_classif.keys():
riming_classif[stratname] = {}
elif type(riming_classif[stratname]) is not dict:
riming_classif[stratname] = {}
# print("Loading "+stratname+" riming classification ...")
for ll in [loc]: # ['pro', 'umd', 'tur', 'afy', 'ank', 'gzt', 'hty', 'svs']:
if ll not in riming_classif[stratname].keys():
riming_classif[stratname][ll] = xr.Dataset()
elif type(riming_classif[stratname][ll]) is not xr.Dataset:
riming_classif[stratname][ll] = xr.Dataset()
for xx in riming_varnames:
try:
riming_classif[stratname][ll] = riming_classif[stratname][ll].assign( xr.open_dataset(realpep_path+"/upload/jgiles/radar_riming_classif"+suffix_name+"/"+stratname+"/"+ll+"_"+xx+".nc") )
print(ll+" "+xx+" riming_classif loaded")
except:
print("!! Not able to load "+stratname+" riming classification !!")
# delete entry if empty
if not riming_classif[stratname][ll]:
del riming_classif[stratname][ll]
r_ds = riming_classif['unfiltered'][loc]
# If z differs slightly due to float precision, snap riming z to qvps z:
if not np.array_equal(r_ds.z.values, qvps.z.values):
r_ds = r_ds.reindex(z=qvps.z, method="nearest", tolerance=25.0)
# If time differs by sub-second noise, snap time to qvps time:
if not np.array_equal(r_ds.time.values, qvps.time.values):
r_ds = r_ds.reindex(time=qvps.time, method="nearest", tolerance=np.timedelta64(1, "m"))
# Assign
qvps = qvps.assign(r_ds)
partial_time = time.time() - p_time
print(f"... took {partial_time/60:.2f} minutes.")
#### Clean ML height values, apply thresholds and make stratiform selections
print("Filtering desired stratiform conditions ...")
p_time = time.time()
if not reload_zarr:
# First define global conditions for the whole dataset, later we will split into chunks
# Use shift(time=1) instead of diff("time") to preserve the exact array length!
diff_bottom = qvps["height_ml_bottom_new_gia"] - qvps["height_ml_bottom_new_gia"].shift(time=1)
cond_ML_bottom_change = abs(diff_bottom) < max_change
cond_ML_bottom_std = qvps["height_ml_bottom_new_gia"].rolling(time=time_window, min_periods=min_period, center=True).std().compute() < max_std
# cond_ML_bottom_minlen = qvps["height_ml_bottom_new_gia"].notnull().rolling(time=5, min_periods=3, center=True).sum().compute()>2
diff_top = qvps["height_ml_new_gia"] - qvps["height_ml_new_gia"].shift(time=1)
cond_ML_top_change = abs(diff_top) < max_change
cond_ML_top_std = qvps["height_ml_new_gia"].rolling(time=time_window, min_periods=min_period, center=True).std().compute() < max_std
# cond_ML_top_minlen = qvps["height_ml_new_gia"].notnull().rolling(time=5, min_periods=3, center=True).sum().compute()>2
allcond = (cond_ML_bottom_change * cond_ML_bottom_std * cond_ML_top_change * cond_ML_top_std).compute()
# Filter out non relevant values
X_SNRH = None
if "SNRHC" in qvps: X_SNRH = "SNRHC"
elif "SNRH" in qvps: X_SNRH = "SNRH"
if X_SNRH is not None:
valid_conditions = (
(qvps[X_TH] > -10 )&
(qvps[X_KDP].fillna(0.) > -0.1)&
(qvps[X_KDP].fillna(0.) < 3)&
(qvps[X_RHO] > 0.7)&
(qvps[X_ZDR] > -1) &
(qvps[X_ZDR] < 3) &
(qvps[X_SNRH] > SNRH_min)
)
else:
print("Could not filter out low SNR")
valid_conditions = (
(qvps[X_TH] > -10 )&
(qvps[X_KDP].fillna(0.) > -0.1)&
(qvps[X_KDP].fillna(0.) < 3)&
(qvps[X_RHO] > 0.7)&
(qvps[X_ZDR] > -1) &
(qvps[X_ZDR] < 3)
)
# Apply to DBZH just to remove empy z coordinates
qvps_dbzh_fil = qvps["DBZH"].where(valid_conditions)
qvps_dbzh_strat_ML_fil = qvps_dbzh_fil.where(allcond)
valid_z = qvps_dbzh_strat_ML_fil.notnull().any(dim="time").compute()
# Fixed-size timestep loop
chunk_size = 5000 # <--- PARAMETRIZABLE: Number of timesteps per batch
total_timesteps = len(qvps.time)
is_first_write = True
print(f"...Dataset has {total_timesteps} total timesteps. Processing in chunks of {chunk_size}...")
for start_idx in range(0, total_timesteps, chunk_size):
# Ensure we don't overshoot the end of the array on the final chunk
end_idx = min(start_idx + chunk_size, total_timesteps)
print(f"\n--- Processing Timesteps {start_idx} to {end_idx-1} ---")
# Isolate RAW data for this chunk lazily using .isel() (Index Selection)
qvps_chunk = qvps.isel(time=slice(start_idx, end_idx))
allcond_chunk = allcond.isel(time=slice(start_idx, end_idx))
valid_conditions_chunk = valid_conditions.isel(time=slice(start_idx, end_idx))
# Filter out non-relevant values
qvps_fil = qvps_chunk.where(valid_conditions_chunk)
# Filter based on conditions
# 1st only ML
qvps_strat_ML_fil = qvps_fil.where(allcond_chunk)
# 2nd fully stratiform pixels (min_entropy >= min_entropy_thresh and ML detected)
cond_entropy = qvps_strat_ML_fil["min_entropy"] >= min_entropy_thresh
qvps_strat_fil = qvps_strat_ML_fil.where(cond_entropy)
# 3d Relaxed alternative: at least 50% of stratiform pixels (min entropy >= min_entropy_thresh and ML detected)
valid_dbzh_count = qvps_strat_ML_fil[X_DBZH].count("z")
cond_relaxed = (cond_entropy.sum("z") >= (valid_dbzh_count / 2)) & (valid_dbzh_count > 0)
qvps_strat_relaxed_fil = qvps_strat_ML_fil.where(cond_relaxed)
# Compute 1D Masks for this specific time chunk
valid_times_ML = allcond_chunk.compute()
valid_times_strat = cond_entropy.any(dim="z").compute()
valid_times_relaxed = cond_relaxed.compute()
# Apply Time masks AND the Global Z mask
qvps_strat_ML_fil = qvps_strat_ML_fil.sel(time=valid_times_ML, z=valid_z)
qvps_strat_fil = qvps_strat_fil.sel(time=valid_times_strat, z=valid_z)
qvps_strat_relaxed_fil = qvps_strat_relaxed_fil.sel(time=valid_times_relaxed, z=valid_z)
# Save filtered QVPs to files
print(" Saving Timestep Chunk to Zarr...")
for stratname, stratqvp_chunk in [("stratiform", qvps_strat_fil.copy()),
("stratiform_relaxed", qvps_strat_relaxed_fil.copy()),
("stratiform_ML", qvps_strat_ML_fil.copy())]:
print(" ... "+stratname)
path_qvpsfil = realpep_path+"/upload/jgiles/stratiform_qvps"+suffix_name+"/"+stratname+"/"+loc+".zarr"
# Clear encoding before chunking
for vv in stratqvp_chunk.data_vars:
stratqvp_chunk[vv].encoding.clear()
stratqvp_chunk[vv].encoding = {'zlib': True, 'complevel': 6}
# Apply optimal chunk shapes
stratqvp_chunk = stratqvp_chunk.chunk({'time': 200, 'z': 200})
if is_first_write:
# BULLETPROOF OVERWRITE: Initialize the Zarr archive cleanly on the very first batch
if os.path.exists(path_qvpsfil):
print(f" ...Removing old archive at {path_qvpsfil}...")
shutil.rmtree(path_qvpsfil)
os.makedirs(os.path.dirname(path_qvpsfil), exist_ok=True)
save_icechunk(stratqvp_chunk, path_qvpsfil, append=False)
else:
# Append subsequent batches
save_icechunk(stratqvp_chunk, path_qvpsfil, append=True)
# Free memory
del qvps_chunk, qvps_fil, stratqvp_chunk
# After the very first chunk successfully processes and writes, turn the flag off
is_first_write = False
# Reload
qvps_strat_fil = open_icechunk(realpep_path+"/upload/jgiles/stratiform_qvps"+suffix_name+"/stratiform/"+loc+".zarr")
qvps_strat_relaxed_fil = open_icechunk(realpep_path+"/upload/jgiles/stratiform_qvps"+suffix_name+"/stratiform_relaxed/"+loc+".zarr")
qvps_strat_ML_fil = open_icechunk(realpep_path+"/upload/jgiles/stratiform_qvps"+suffix_name+"/stratiform_ML/"+loc+".zarr")
partial_time = time.time() - p_time
print(f"... took {partial_time/60:.2f} minutes.")
#### Filter retrievals and riming like the QVPs
print("Filter retrievals and riming like the QVPs ...")
p_time = time.time()
print("... QVP-based retrievals ...")
for stratname, stratqvp in [("stratiform", qvps_strat_fil.copy()),
("stratiform_relaxed", qvps_strat_relaxed_fil.copy()),
("stratiform_ML", qvps_strat_ML_fil.copy())]:
print(" ... "+stratname)
retrievals_qvpbased[stratname] = {}
path_qvpretrievals = realpep_path+"/upload/jgiles/radar_retrievals_QVPbased"+suffix_name+"/"+stratname+"/"+loc+".zarr"
if calculate_retrievals:
retrievals_qvpbased[stratname][loc] = retrievals_qvpbased["unfiltered"][loc].where(stratqvp[X_TH])
# Clear encoding before chunking
for vv in retrievals_qvpbased[stratname][loc].data_vars:
retrievals_qvpbased[stratname][loc][vv].encoding.clear()
retrievals_qvpbased[stratname][loc][vv].encoding = {'zlib': True, 'complevel': 6}
# Apply optimal chunk shapes
retrievals_qvpbased[stratname][loc] = retrievals_qvpbased[stratname][loc].chunk({'time': 200, 'z': 200})
# Save retrievals
# BULLETPROOF OVERWRITE: Initialize the Zarr archive cleanly
if os.path.exists(path_qvpretrievals):
shutil.rmtree(path_qvpretrievals)
os.makedirs(os.path.dirname(path_qvpretrievals), exist_ok=True)
save_icechunk(retrievals_qvpbased[stratname][loc], path_qvpretrievals, append=False)
# reload
retrievals_qvpbased[stratname][loc] = open_icechunk(path_qvpretrievals)
print("... PPI-based retrievals ...")
for stratname, stratqvp in [("stratiform", qvps_strat_fil.copy()),
("stratiform_relaxed", qvps_strat_relaxed_fil.copy()),
("stratiform_ML", qvps_strat_ML_fil.copy())]:
print(" ... "+stratname)
retrievals[stratname] = {}
path_retrievals = realpep_path+"/upload/jgiles/radar_retrievals"+suffix_name+"/"+stratname+"/"+loc+".zarr"
if calculate_retrievals:
retrievals[stratname][loc] = xr.Dataset({key: stratqvp[key] for key in retrievals_namelist if key in stratqvp.data_vars})
# Clear encoding before chunking
for vv in retrievals[stratname][loc].data_vars:
retrievals[stratname][loc][vv].encoding.clear()
retrievals[stratname][loc][vv].encoding = {'zlib': True, 'complevel': 6}
# Apply optimal chunk shapes
retrievals[stratname][loc] = retrievals[stratname][loc].chunk({'time': 200, 'z': 200})
# Save retrievals
# BULLETPROOF OVERWRITE: Initialize the Zarr archive cleanly
if os.path.exists(path_retrievals):
shutil.rmtree(path_retrievals)
os.makedirs(os.path.dirname(path_retrievals), exist_ok=True)
save_icechunk(retrievals[stratname][loc], path_retrievals, append=False)
# reload
retrievals[stratname][loc] = open_icechunk(path_retrievals)
print("...riming ...")
for stratname, stratqvp in [("stratiform", qvps_strat_fil.copy()),
("stratiform_relaxed", qvps_strat_relaxed_fil.copy()),
("stratiform_ML", qvps_strat_ML_fil.copy())]:
print(" ... "+stratname)
if stratname not in riming_classif.keys():
riming_classif[stratname] = {}
elif type(riming_classif[stratname]) is not dict:
riming_classif[stratname] = {}
# print("Loading "+stratname+" riming classification ...")
for ll in [loc]: # ['pro', 'umd', 'tur', 'afy', 'ank', 'gzt', 'hty', 'svs']:
riming_classif[stratname][ll] = stratqvp[riming_varnames]
# Clear encoding before chunking
for vv in riming_classif[stratname][ll].data_vars:
riming_classif[stratname][ll][vv].encoding.clear()
riming_classif[stratname][ll][vv].encoding = {'zlib': True, 'complevel': 6}
# Apply optimal chunk shapes
riming_classif[stratname][ll] = riming_classif[stratname][ll].chunk({'time': 200, 'z': 200})
# Save riming to files
for xx in riming_varnames:
try:
path_riming = realpep_path+"/upload/jgiles/radar_riming_classif"+suffix_name+"/"+stratname+"/"+ll+"_"+xx+".nc"
os.makedirs(os.path.dirname(path_riming), exist_ok=True)
with dask.config.set(scheduler='single-threaded'):
riming_classif[stratname][ll][xx].to_netcdf(path_riming, engine='h5netcdf')
except:
print("!! Not able to extract "+stratname+" riming classification !!")
# delete entry if empty
if not riming_classif[stratname][ll]:
del riming_classif[stratname][ll]
partial_time = time.time() - p_time
print(f"... took {partial_time/60:.2f} minutes.")
#### General statistics
print("Calculating statistics ...")
p_time = time.time()
# define generalized variables to subset to avoid memory crashes
to_include = ["DBZH", "RHOHV", "ZDR_EC_OC" , "KDP_ML_corrected", "RH", "min_entropy",
"Dm_", "iwc_", "lwc_", "Nt_", "PHIDP_UF_OC", "UPHIDP_UF_OC"]
z_snow_over_ML = 300 # set the height above the ML from where to consider snow. 300 m like in https://doi.org/10.1175/JAMC-D-19-0128.1
z_rain_below_ML = 300 # set the height below the ML from where to consider rain. 300 m like in https://doi.org/10.1175/JAMC-D-19-0128.1
z_grad_above_ML = 2000 # height above the ML until which to compute the gradient
# We will put the final stats in a dict
try: # check if exists, if not, create it
stats
except NameError:
stats = {}
for stratname, stratqvp0 in [("stratiform", qvps_strat_fil.copy()),
("stratiform_relaxed", qvps_strat_relaxed_fil.copy()),
("stratiform_ML", qvps_strat_ML_fil.copy())]:
print(" ... for "+stratname)
# Iterate through data_vars and keep those that match ANY of the substrings
prefixes = tuple(to_include)
vars_to_keep = [
var for var in stratqvp0.data_vars
if str(var).startswith(prefixes)
]
# Subset the dataset (xarray will automatically keep all coordinates like time, z)
stratqvp0 = stratqvp0[vars_to_keep]
# Drop range and z_idx from stratqvp0 so they never cause coordinate mismatches across chunks
drop_c = [c for c in ["range", "z_idx"] if c in stratqvp0.coords]
if drop_c:
stratqvp0 = stratqvp0.drop_vars(drop_c)
stats[stratname] = {}
chunk_size = 1000
total_timesteps = stratqvp0.sizes["time"]
print(f" Dataset has {total_timesteps} timesteps. Processing entirely in RAM in chunks of {chunk_size} ...")
chunk_results_list = []
for start_idx in range(0, total_timesteps, chunk_size):
end_idx = min(start_idx + chunk_size, total_timesteps)
print(f" -> Timesteps {start_idx} to {end_idx-1}...")
# PULL BATCH DIRECTLY INTO RAM! All subsequent math is instantaneous and Dask-free.
stratqvp = stratqvp0.isel(time=slice(start_idx, end_idx)).compute().copy()
values_sfc = stratqvp.where( (stratqvp["z"] < (stratqvp["height_ml_bottom_new_gia"]+stratqvp["z"][0])/2) ).bfill("z").isel({"z": 0}) # selects the closest value to the ground starting from below half of the ML height (with respect to the radar altitude)
values_snow = stratqvp.where( (stratqvp["z"] > stratqvp["height_ml_new_gia"]) ).sel({"z": stratqvp["height_ml_new_gia"] + z_snow_over_ML}, method="nearest", tolerance=z_snow_over_ML)
values_rain = stratqvp.where( (stratqvp["z"] < stratqvp["height_ml_bottom_new_gia"]) )\
.sel({"z": (stratqvp["height_ml_bottom_new_gia"] - z_rain_below_ML)\
.clip(min=stratqvp["z"].min()-z_rain_below_ML)}, # added clip because rounding errors may cause the ML bot to be slighly below the minimum z
method="nearest", tolerance=z_rain_below_ML)
##### ML statistics
# select values inside the ML
qvps_ML = stratqvp.where( ((stratqvp["z"] < stratqvp["height_ml_new_gia"]) & \
(stratqvp["z"] > stratqvp["height_ml_bottom_new_gia"])), #.compute(),
#drop=True
)
values_ML_max = qvps_ML.max(dim="z")
values_ML_min = qvps_ML.min(dim="z")
values_ML_mean = qvps_ML.mean(dim="z")
ML_thickness = (qvps_ML["height_ml_new_gia"] - qvps_ML["height_ml_bottom_new_gia"]).rename("ML_thickness")
ML_bottom = qvps_ML["height_ml_bottom_new_gia"]
ML_bottom_TEMP = stratqvp["TEMP"].sel(z=stratqvp["height_ml_bottom_new_gia"], method="nearest")
ML_thickness_TEMP = ML_bottom_TEMP - stratqvp["TEMP"].sel(z=stratqvp["height_ml_new_gia"], method="nearest")
#!!! Temporary solution with xr.ufuncs.isfinite because there are -inf and inf values in ANK data
# Always drop z-dependent coordinates ("range", "z_idx") to avoid merge errors and chunk-to-chunk coordinate mismatches
drop_coords = [c for c in ["range", "z_idx"] if c in qvps_ML.coords]
qvps_ML_clean = qvps_ML.drop_vars(drop_coords) if drop_coords else qvps_ML
height_ML_max = qvps_ML_clean.where(xr.ufuncs.isfinite(qvps_ML_clean)).idxmax("z", skipna=True)
height_ML_min = qvps_ML_clean.where(xr.ufuncs.isfinite(qvps_ML_clean)).idxmin("z", skipna=True)
# Silke style
# select timesteps with detected ML
# gradient_silke = stratqvp.where(stratqvp["height_ml_new_gia"] > stratqvp["height_ml_bottom_new_gia"], drop=True)
# gradient_silke_ML = gradient_silke.sel({"z": gradient_silke["height_ml_new_gia"]}, method="nearest")
# gradient_silke_ML_plus_2km = gradient_silke.sel({"z": gradient_silke_ML["z"]+2000}, method="nearest")
# gradient_final = (gradient_silke_ML_plus_2km - gradient_silke_ML)/2
# beta = gradient_final[X_TH] #### TH OR DBZH??
# Gradient above the ML
# We select above z_snow_over_ML and below z_snow_over_ML + z_grad_above_ML
# Then we compute the gradient as the linear fit of the valid values
cond_above_ML2km = ( (stratqvp["z"] > (stratqvp["height_ml_new_gia"] + z_snow_over_ML) ) &
(stratqvp["z"] < (stratqvp["height_ml_new_gia"] + z_snow_over_ML + z_grad_above_ML) ) )#.compute()
stratqvp_ = stratqvp.where(cond_above_ML2km).copy()
stratqvp_TEMP = stratqvp["TEMP"].where(cond_above_ML2km).copy()
beta = stratqvp_.polyfit("z", 1, skipna=True).isel(degree=0) * 1000 # x1000 to transform the gradients to /km
beta = beta.rename({var: var.replace("_polyfit_coefficients", "") for var in beta.data_vars}).assign_coords(
{"valid_count": stratqvp_["DBZH"].count("z"),
"valid_perc": stratqvp_["DBZH"].count("z")/stratqvp_TEMP.count("z")})
# Variation: Gradient above the ML until the DGL bottom
cond_above_ML_below_DGL = ( (stratqvp["TEMP"] >= -10) &
(stratqvp["z"] > (stratqvp["height_ml_new_gia"] + z_snow_over_ML) ) )# .compute()
stratqvp_belowDGL_ = stratqvp.where(cond_above_ML_below_DGL).copy()
stratqvp_belowDGL_TEMP = stratqvp["TEMP"].where(cond_above_ML_below_DGL).copy()
beta_belowDGL = stratqvp_belowDGL_.polyfit("z", 1, skipna=True).isel(degree=0) * 1000 # x1000 to transform the gradients to /km
beta_belowDGL = beta_belowDGL.rename({var: var.replace("_polyfit_coefficients", "") for var in beta_belowDGL.data_vars}).assign_coords(
{"valid_count": stratqvp_belowDGL_["DBZH"].count("z"),
"valid_perc": stratqvp_belowDGL_["DBZH"].count("z")/stratqvp_belowDGL_TEMP.count("z")})
# Gradient below the ML
# We select below z_rain_below_ML
# Then we compute the gradient as the linear fit of the valid values
cond_below_ML = ( stratqvp["z"] < (stratqvp["height_ml_bottom_new_gia"] - z_rain_below_ML ) )# .compute()
stratqvp_belowML_ = stratqvp.where(cond_below_ML).copy()
stratqvp_belowML_TEMP = stratqvp["TEMP"].where(cond_below_ML).copy()
beta_belowML = stratqvp_belowML_.polyfit("z", 1, skipna=True).isel(degree=0) * 1000 # x1000 to transform the gradients to /km
beta_belowML = beta_belowML.rename({var: var.replace("_polyfit_coefficients", "") for var in beta_belowML.data_vars}).assign_coords(
{"valid_count": stratqvp_belowML_["DBZH"].count("z"),
"valid_perc": stratqvp_belowML_["DBZH"].count("z")/stratqvp_belowML_TEMP.count("z")})
# Cloud top (3 methods)
# Get the height value of the last not null value with a minimum of entropy 0.2 (this min entropy is to filter out random noise pixels)
cond_cloudtop = ( (stratqvp["z"] > stratqvp["height_ml_new_gia"]) & (stratqvp["min_entropy"] > 0.2 ) )# .compute()
cloudtop = stratqvp[X_DBZH].where(cond_cloudtop) \
.isel(z=slice(None,None,-1)).notnull().idxmax("z").rename("cloudtop")
# Get the height value of the last value > 5 dBZ
cond_cloudtop5 = ( (stratqvp["z"] > stratqvp["height_ml_new_gia"]) & (stratqvp["min_entropy"] > 0.2 ) & (stratqvp[X_DBZH]>5) )# .compute()
cloudtop_5dbz = stratqvp[X_DBZH].where(cond_cloudtop5) \
.isel(z=slice(None,None,-1)).notnull().idxmax("z").rename("cloudtop 5 dBZ")
# Get the height value of the last value > 10 dBZ
cond_cloudtop10 = ( (stratqvp["z"] > stratqvp["height_ml_new_gia"]) & (stratqvp["min_entropy"] > 0.2 ) & (stratqvp[X_DBZH]>10) )# .compute()
cloudtop_10dbz = stratqvp[X_DBZH].where(cond_cloudtop10) \
.isel(z=slice(None,None,-1)).notnull().idxmax("z").rename("cloudtop 10 dBZ")
# Temperature of the cloud top (3 methods)
cloudtop_TEMP = stratqvp["TEMP"].sel({"z": cloudtop}, method="nearest")
cloudtop_TEMP_5dbz = stratqvp["TEMP"].sel({"z": cloudtop_5dbz}, method="nearest")
cloudtop_TEMP_10dbz = stratqvp["TEMP"].sel({"z": cloudtop_10dbz}, method="nearest")
##### DGL statistics
# select values in the DGL
cond_DGL = ( (stratqvp["TEMP"] >= -20) & (stratqvp["TEMP"] <= -10) )# .compute()
qvps_DGL = stratqvp.where(cond_DGL)#, drop=True)
values_DGL_max = qvps_DGL.max(dim="z")
values_DGL_min = qvps_DGL.min(dim="z")
values_DGL_mean = qvps_DGL.mean(dim="z")
##### Needle zone statistics
# select values in the NZ
# qvps_NZ = stratqvp.where(((stratqvp["TEMP"] >= -8)&(stratqvp["TEMP"] <= -1)).compute(), drop=True).unify_chunks()
cond_NZ = ( (stratqvp["TEMP"] >= -8) & (stratqvp["TEMP"] <= -1) )# .compute()
qvps_NZ = stratqvp.where(cond_NZ)
values_NZ_max = qvps_NZ.max(dim="z")
values_NZ_min = qvps_NZ.min(dim="z")
values_NZ_mean = qvps_NZ.mean(dim="z")
# Put in the dictionary
chunk_stats_dict = {
"values_sfc": values_sfc.assign_attrs({"Description": "value closest to the ground (at least lower than half of the ML height)"}).copy(deep=True),
"values_snow": values_snow.assign_attrs({"Description": "value in snow ("" m above the ML)"}).copy(deep=True),
"values_rain": values_rain.assign_attrs({"Description": "value in rain ("+str(z_rain_below_ML)+" m above the ML)"}).copy(deep=True),
"values_ML_max": values_ML_max.assign_attrs({"Description": "maximum value within the ML"}).copy(deep=True),
"values_ML_min": values_ML_min.assign_attrs({"Description": "minimum value within the ML"}).copy(deep=True),
"values_ML_mean": values_ML_mean.assign_attrs({"Description": "mean value within the ML"}).copy(deep=True),
"height_ML_max": height_ML_max.assign_attrs({"Description": "height (z) of the maximum value within the ML"}).copy(deep=True),
"height_ML_min": height_ML_min.assign_attrs({"Description": "height (z) of the minimum value within the ML"}).copy(deep=True),
"ML_thickness": ML_thickness.assign_attrs({"Description": "thickness of the ML (in m)"}).copy(deep=True),
"ML_bottom": ML_bottom.assign_attrs({"Description": "height of the ML bottom (in m)"}).copy(deep=True),
"ML_thickness_TEMP": ML_thickness_TEMP.assign_attrs({"Description": "thickness of the ML (in temperature)"}).copy(deep=True),
"ML_bottom_TEMP": ML_bottom_TEMP.assign_attrs({"Description": "height of the ML bottom (in temperature)"}).copy(deep=True),
"values_DGL_max": values_DGL_max.assign_attrs({"Description": "maximum value within the DGL"}).copy(deep=True),
"values_DGL_min": values_DGL_min.assign_attrs({"Description": "minimum value within the DGL"}).copy(deep=True),
"values_DGL_mean": values_DGL_mean.assign_attrs({"Description": "mean value within the DGL"}).copy(deep=True),
"values_NZ_max": values_NZ_max.assign_attrs({"Description": "maximum value within the NZ"}).copy(deep=True),
"values_NZ_min": values_NZ_min.assign_attrs({"Description": "minimum value within the NZ"}).copy(deep=True),
"values_NZ_mean": values_NZ_mean.assign_attrs({"Description": "mean value within the NZ"}).copy(deep=True),
"beta": beta.assign_attrs({"Description": "Gradient from "+str(z_snow_over_ML)+" to "+str(z_grad_above_ML)+" m above the ML"}).copy(deep=True),
"beta_belowDGL": beta_belowDGL.assign_attrs({"Description": "Gradient from "+str(z_snow_over_ML)+" m above the ML to DGL bottom"}).copy(deep=True),
"beta_belowML": beta_belowML.assign_attrs({"Description": "Gradient from the first valid value to "+str(z_rain_below_ML)+" m below the ML"}).copy(deep=True),
"cloudtop": cloudtop.assign_attrs({"Description": "Cloud top height (highest not-null ZH value)"}).copy(deep=True),
"cloudtop_5dbz": cloudtop_5dbz.assign_attrs({"Description": "Cloud top height (highest ZH value > 5 dBZ)"}).copy(deep=True),
"cloudtop_10dbz": cloudtop_10dbz.assign_attrs({"Description": "Cloud top height (highest ZH value > 10 dBZ)"}).copy(deep=True),
"cloudtop_TEMP": cloudtop_TEMP.assign_attrs({"Description": "TEMP at cloud top height (highest not-null ZH value)"}).copy(deep=True),
"cloudtop_TEMP_5dbz": cloudtop_TEMP_5dbz.assign_attrs({"Description": "TEMP at cloud top height (highest ZH value > 5 dBZ)"}).copy(deep=True),
"cloudtop_TEMP_10dbz": cloudtop_TEMP_10dbz.assign_attrs({"Description": "TEMP at cloud top height (highest ZH value > 10 dBZ)"}).copy(deep=True),
}
# Package into a dataset and append to our master list
chunk_results_list.append(chunk_stats_dict)
# Explicitly free memory for this chunk!
del stratqvp, chunk_stats_dict
# Stitch chunks back together
print(" ... concatenating all time steps...")
stats[stratname][loc] = {}
# Grab the keys from the first chunk
# (e.g. "values_sfc", "values_snow", etc.)
stat_keys = chunk_results_list[0].keys()
for key in stat_keys:
# Ensure range and z_idx are stripped from all chunks before concatenating
cleaned_chunks = [
chunk[key].drop_vars([c for c in ["range", "z_idx"] if c in chunk[key].coords])
for chunk in chunk_results_list
]
# Concatenate the individual datasets for each specific stat
stats[stratname][loc][key] = xr.concat(cleaned_chunks, dim="time", coords="minimal", compat="override")
# Free the chunk list memory
del chunk_results_list
# Save files
print(" ... saving to NetCDF...")
save_dir = realpep_path+"/upload/jgiles/radar_stats"+suffix_name+"/"+stratname
os.makedirs(save_dir, exist_ok=True)
# Iterate through the dictionary of datasets
for xx, stat_obj in stats[stratname][loc].items():
# Safe Encoding mapping
if isinstance(stat_obj, xr.Dataset):
for vv in stat_obj.data_vars:
stat_obj[vv].encoding.clear()
stat_obj[vv].encoding = {'zlib': True, 'complevel': 6}
else:
stat_obj.encoding.clear()