-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatilda_functions.py
More file actions
1400 lines (1170 loc) · 57.8 KB
/
matilda_functions.py
File metadata and controls
1400 lines (1170 loc) · 57.8 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
import os
import pyproj
os.environ['PROJ_LIB'] = pyproj.datadir.get_data_dir()
import requests
import concurrent.futures
import seaborn as sns
import probscale
import math
import matplotlib.pyplot as plt
import pandas as pd
import warnings
import geopandas as gpd
import ee
import geemap
import pickle
import numpy as np
from retry import retry
from tqdm import tqdm
from bias_correction import BiasCorrection
from matplotlib.legend import Legend
# warnings.filterwarnings("ignore")
def read_era5l(file):
"""Reads ERA5-Land data, standardizes to match CHELSA format for further processing"""
# Try to read 'dt' if available, otherwise fall back to 'date'
temp_df = pd.read_csv(file, nrows=1)
time_col = 'dt' if 'dt' in temp_df.columns else 'date'
df = pd.read_csv(file, usecols=['temp', 'prec', time_col], parse_dates=[time_col])
df = df.set_index(time_col).resample('D').agg({'temp': 'mean', 'prec': 'sum'})
df = df.rename(columns={'temp': 'tas', 'prec': 'pr'})
df['tas'] = df['tas'].round(2)
df['pr'] = df['pr'].round(4)
df.index.name = "time"
return df
class CMIPDownloader:
"""Class to download spatially averaged CMIP6 data for a given period, variable, and spatial subset."""
def __init__(self, var, starty, endy, shape, processes=10, dir='./'):
self.var = var
self.starty = starty
self.endy = endy
self.shape = shape
self.processes = processes
self.directory = dir
# create the download directory if it doesn't exist
if not os.path.exists(self.directory):
os.makedirs(self.directory)
def get_area(self):
"""Load a polygon from file and calculate area in square meters.
Stores the area as self.area_m2.
"""
# Compute area from EE geometry (client-side)
try:
self.area_m2 = self.shape.geometry().area().getInfo()
except Exception as e:
print("Could not retrieve area from EE geometry:", e)
self.area_m2 = None
print(f'Polygon area: {round(self.area_m2, 2)} m²')
def download(self):
"""Runs a subset routine for CMIP6 data on GEE servers to create ee.FeatureCollections for all years in
the requested period. Downloads individual years in parallel processes to decrease the download time."""
print('Initiating download request for NEX-GDDP-CMIP6 data from ' +
str(self.starty) + ' to ' + str(self.endy) + '.')
self.get_area()
use_fallback = self.area_m2 < 2e6 # client-side check for small polygons
print('Scaling to 500m for small polygons.' if use_fallback else 'Scaling to native resolution for large polygons.')
def getRequests(starty, endy):
"""Generates a list of years to be downloaded. [Client side]"""
return [i for i in range(starty, endy + 1)]
@retry(tries=10, delay=1, backoff=2)
def getResult(index, year):
"""Handle the HTTP requests to download one year of CMIP6 data. [Server side]"""
start = str(year) + '-01-01'
end = str(year + 1) + '-01-01'
startDate = ee.Date(start)
endDate = ee.Date(end)
n = endDate.difference(startDate, 'day').subtract(1)
def getImageCollection(var):
"""Create and image collection of CMIP6 data for the requested variable, period, and region.
[Server side]"""
collection = (ee.ImageCollection('NASA/GDDP-CMIP6')
.select(var)
.filterDate(startDate, endDate)
.filter(ee.Filter.neq('model', 'NorESM2-LM')) # Exclude model (missing year 2096)
# .filterBounds(self.shape)
)
return collection
def renameBandName(b):
"""Edit variable names for better readability. [Server side]"""
split = ee.String(b).split('_')
return ee.String(split.splice(split.length().subtract(2), 1).join("_"))
def buildFeature(i):
"""Extract daily data with strategy based on polygon area. [Server side]"""
t1 = startDate.advance(i, 'day')
t2 = t1.advance(1, 'day')
dailyColl = collection.filterDate(t1, t2)
dailyImg = dailyColl.toBands()
# Rename bands
bands = dailyImg.bandNames()
renamed = bands.map(renameBandName)
image = dailyImg.rename(renamed)
if use_fallback:
result_dict = image.reduceRegion(
reducer=ee.Reducer.mean(),
geometry=self.shape,
scale=500
)
else:
result_dict = image.reduceRegion(
reducer=ee.Reducer.mean(),
geometry=self.shape,
scale=500 # in few cases native resolution fails nonetheless, so 500 for all...
)
result_dict = result_dict.combine(
ee.Dictionary({
'system:time_start': t1.millis(),
'isodate': t1.format('YYYY-MM-dd')})
)
return ee.Feature(None, result_dict)
# Create features for all days in the respective year. [Server side]
collection = getImageCollection(self.var)
year_feature = ee.FeatureCollection(ee.List.sequence(0, n).map(buildFeature))
# Create a download URL for a CSV containing the feature collection. [Server side]
url = year_feature.getDownloadURL()
# Handle downloading the actual csv for one year. [Client side]
r = requests.get(url, stream=True)
if r.status_code != 200:
r.raise_for_status()
filename = os.path.join(self.directory, 'cmip6_' + self.var + '_' + str(year) + '.csv')
with open(filename, 'w') as f:
f.write(r.text)
return index
# Create a list of years to be downloaded. [Client side]
items = getRequests(self.starty, self.endy)
# Launch download requests in parallel processes and display a status bar. [Client side]
with tqdm(total=len(items), desc="Downloading CMIP6 data for variable '" + self.var + "'") as pbar:
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=self.processes) as executor:
for i, year in enumerate(items):
results.append(executor.submit(getResult, i, year))
for future in concurrent.futures.as_completed(results):
index = future.result()
pbar.update(1)
print("All downloads complete.")
class CMIPProcessor:
"""Class to read and pre-process CSV files downloaded by the CMIPDownloader class."""
def __init__(self, var, file_dir='.', start=1979, end=2100):
self.file_dir = file_dir
self.var = var
self.start = start
self.end = end
self.df_hist = self.append_df(self.var, self.start, self.end, self.file_dir, hist=True)
self.df_ssp = self.append_df(self.var, self.start, self.end, self.file_dir, hist=False)
self.ssp2_common, self.ssp5_common, self.hist_common, \
self.common_models, self.dropped_models = self.process_dataframes()
self.ssp2, self.ssp5 = self.get_results()
def read_cmip(self, filename):
"""Reads CMIP6 CSV files and drops redundant columns."""
df = pd.read_csv(filename, index_col='isodate', parse_dates=['isodate'])
df = df.drop(['system:index', '.geo', 'system:time_start'], axis=1)
return df
def append_df(self, var, start, end, file_dir='.', hist=True):
"""Reads CMIP6 CSV files of individual years and concatenates them into dataframes for the full downloaded
period. Historical and scenario datasets are treated separately. Converts precipitation unit to mm."""
df_list = []
if hist:
starty = start
endy = 2014
else:
starty = 2015
endy = end
for i in range(starty, endy + 1):
filename = file_dir + 'cmip6_' + var + '_' + str(i) + '.csv'
df_list.append(self.read_cmip(filename))
if hist:
hist_df = pd.concat(df_list)
if var == 'pr':
hist_df = hist_df * 86400 # from kg/(m^2*s) to mm/day
return hist_df
else:
ssp_df = pd.concat(df_list)
if var == 'pr':
ssp_df = ssp_df * 86400 # from kg/(m^2*s) to mm/day
return ssp_df
def process_dataframes(self):
"""Separates the two scenarios and drops models not available for both scenarios and the historical period."""
ssp2 = self.df_ssp.loc[:, self.df_ssp.columns.str.startswith('ssp245')]
ssp5 = self.df_ssp.loc[:, self.df_ssp.columns.str.startswith('ssp585')]
hist = self.df_hist.loc[:, self.df_hist.columns.str.startswith('historical')]
ssp2.columns = ssp2.columns.str.lstrip('ssp245_').str.rstrip('_' + self.var)
ssp5.columns = ssp5.columns.str.lstrip('ssp585_').str.rstrip('_' + self.var)
hist.columns = hist.columns.str.lstrip('historical_').str.rstrip('_' + self.var)
# Get all the models the three datasets have in common
common_models = set(ssp2.columns).intersection(ssp5.columns).intersection(hist.columns)
# Get the model names that contain NaN values
nan_models_list = [df.columns[df.isna().any()].tolist() for df in [ssp2, ssp5, hist]]
# flatten the list
nan_models = [col for sublist in nan_models_list for col in sublist]
# remove duplicates
nan_models = list(set(nan_models))
# Remove models with NaN values from the list of common models
common_models = [x for x in common_models if x not in nan_models]
ssp2_common = ssp2.loc[:, common_models]
ssp5_common = ssp5.loc[:, common_models]
hist_common = hist.loc[:, common_models]
dropped_models = list(set([mod for mod in ssp2.columns if mod not in common_models] +
[mod for mod in ssp5.columns if mod not in common_models] +
[mod for mod in hist.columns if mod not in common_models]))
return ssp2_common, ssp5_common, hist_common, common_models, dropped_models
def get_results(self):
"""Concatenates historical and scenario data to combined dataframes of the full downloaded period.
Arranges the models in alphabetical order."""
ssp2_full = pd.concat([self.hist_common, self.ssp2_common])
ssp2_full.index.names = ['TIMESTAMP']
ssp5_full = pd.concat([self.hist_common, self.ssp5_common])
ssp5_full.index.names = ['TIMESTAMP']
ssp2_full = ssp2_full.reindex(sorted(ssp2_full.columns), axis=1)
ssp5_full = ssp5_full.reindex(sorted(ssp5_full.columns), axis=1)
return ssp2_full, ssp5_full
def build_data_chunks(train_start='1950-01-02'):
"""
Constructs a list of non-overlapping correction and extraction periods for iterative bias adjustment in discrete
chunks of data.
The periods follow a standardized decadal pattern:
- The first period starts at the specified `train_start` date and spans 30 years for correction,
with a 10-year extraction window.
- Subsequent extraction periods follow full decades (e.g., 1981–1990, 1991–2000, ...),
with corresponding 30-year correction windows centered around the extraction decade.
- The final period covers 2081–2100 for extraction and 2071–2100 for correction.
Parameters
----------
train_start : str, optional
The starting date of the training data in 'YYYY-MM-DD' format. Default is '1950-01-02'.
Returns
-------
correction_periods : list of dict
A list of dictionaries, each with keys:
- 'correction_range': (str, str), start and end dates of the correction window.
- 'extraction_range': (str, str), start and end dates of the extraction window.
"""
train_start_year = pd.to_datetime(train_start).year
def round_up10(number):
return math.ceil(number / 10) * 10
decade_start = round_up10(train_start_year)
correction_periods = []
# Define the first correction period based on the train start year
correction_periods.append({'correction_range': (train_start, f'{decade_start + 30}-12-31'),
'extraction_range': (train_start, f'{decade_start + 10}-12-31')})
# Define the standard extraction decades
for decade_start in range(decade_start + 1, 2081, 10):
extraction_start = decade_start
extraction_end = decade_start + 9
correction_start = extraction_start - 10
correction_end = extraction_end + 10
# Only include periods where the correction window fits the available data
if correction_start >= train_start_year:
correction_periods.append({
'correction_range': (f'{correction_start}-01-01', f'{correction_end}-12-31'),
'extraction_range': (f'{extraction_start}-01-01', f'{extraction_end}-12-31')
})
# Define the last extraction period
correction_periods.append({'correction_range': ('2071-01-01', '2100-12-31'),
'extraction_range': ('2081-01-01', '2100-12-31')})
return correction_periods
def adjust_bias(predictand, predictor, datasource='era5l',
train_start='1950-01-02', train_end='2024-12-31',
method='normal_mapping'):
"""
Adjusts for the bias between target data and the historic CMIP6 model runs.
Optionally replaces training period with reanalysis for consistent output.
"""
# Convert train_start to datetime and extract the year
train_start_year = pd.to_datetime(train_start).year
# Read predictor data
var = 'tas' if predictand.mean().mean() > 100 else 'pr'
# Build discrete chunks of data for bias correction
correction_periods = build_data_chunks(train_start)
# Initialize empty DataFrame for corrected data
corrected_data = pd.DataFrame()
# Shared training period
training_period = slice(train_start, train_end)
for period in correction_periods:
correction_start, correction_end = period['correction_range']
extraction_start, extraction_end = period['extraction_range']
correction_slice = slice(correction_start, correction_end)
extraction_slice = slice(extraction_start, extraction_end)
data_corr = pd.DataFrame()
for col in predictand.columns:
x_train = predictand[col][training_period].squeeze()
y_train = predictor[training_period][var].squeeze()
x_predict = predictand[col][correction_slice].squeeze()
bc_corr = BiasCorrection(y_train, x_train, x_predict)
corrected_col = pd.DataFrame(bc_corr.correct(method=method))
data_corr[col] = corrected_col.loc[extraction_slice]
# Clamp negative precipitation to 0
if var in ['prec', 'pr']:
data_corr[data_corr < 0] = 0
corrected_data = pd.concat([corrected_data, data_corr])
# Replace part of the data with reanalysis if applicable
if datasource == 'chelsa':
raw_train = predictand.loc[train_start:'2016-12-31']
corrected_train = corrected_data.loc[train_start:'2016-12-31']
predictor_hist = predictor.loc[train_start:'2016-12-31', var].to_frame()
predictor_hist = pd.DataFrame(
np.tile(predictor_hist.values, (1, len(predictand.columns))),
columns=predictand.columns,
index=predictor_hist.index
)
predictor_hist.index.name = 'TIMESTAMP'
corrected_future = corrected_data.loc['2017-01-01':]
corrected_data = pd.concat([predictor_hist, corrected_future])
corrected_data.sort_index(inplace=True)
corrected_data.index.name = 'TIMESTAMP'
return corrected_data, raw_train, corrected_train
elif datasource == 'era5l':
raw_train = predictand.loc[train_start:train_end]
corrected_train = corrected_data.loc[(corrected_data.index >= train_start) & (corrected_data.index <= train_end)]
predictor_hist = predictor.loc[train_start:train_end, var].to_frame()
predictor_hist = pd.DataFrame(
np.tile(predictor_hist.values, (1, len(predictand.columns))),
columns=predictand.columns,
index=predictor_hist.index
)
predictor_hist.index.name = 'TIMESTAMP'
corrected_future = corrected_data.loc[train_end:].copy()
corrected_data = pd.concat([predictor_hist, corrected_future])
corrected_data.sort_index(inplace=True)
corrected_data.index.name = 'TIMESTAMP'
return corrected_data, raw_train, corrected_train
else:
corrected_data.sort_index(inplace=True)
corrected_data.index.name = 'TIMESTAMP'
return corrected_data
class CMIP6PolygonProcessor:
"""
Fork of the CMIP6DataProcessor to work with a general polygon and CHELSA-W5E5 data instead of weather stations.
"""
def __init__(self, polygon_path, gee_project, starty, endy, cmip_dir, reanalysis, reanalysis_dir, processes):
self.polygon_path = polygon_path
self.poly_name = os.path.splitext(os.path.basename(polygon_path))[0]
self.gee_project = gee_project
self.starty = starty
self.endy = endy
self.cmip_dir = cmip_dir
self.reanalysis = reanalysis
self.reanalysis_dir = reanalysis_dir
self.processes = processes
def initialize_target(self):
try:
ee.Initialize(project=self.gee_project)
except Exception:
ee.Authenticate()
ee.Initialize(project=self.gee_project)
shape = gpd.read_file(self.polygon_path)
self.polygon_ee = geemap.geopandas_to_ee(shape)
def download_cmip6_data(self):
self.initialize_target()
downloader_t = CMIPDownloader('tas', self.starty, self.endy, self.polygon_ee, self.processes, self.cmip_dir)
downloader_t.download()
downloader_p = CMIPDownloader('pr', self.starty, self.endy, self.polygon_ee, self.processes, self.cmip_dir)
downloader_p.download()
def process_cmip6_data(self):
processor_t = CMIPProcessor('tas', self.cmip_dir, self.starty, self.endy)
self.ssp2_tas_raw, self.ssp5_tas_raw = processor_t.get_results()
processor_p = CMIPProcessor('pr', self.cmip_dir, self.starty, self.endy)
self.ssp2_pr_raw, self.ssp5_pr_raw = processor_p.get_results()
def bias_adjustment(self):
self.initialize_target()
self.process_cmip6_data()
print('Running bias adjustment routine...')
if self.reanalysis == 'era5l':
# Load ERA5-Land data
era5l_file = os.path.join(self.reanalysis_dir, f"era5l_{self.poly_name}.csv")
era5l_data = read_era5l(era5l_file)
tas_target = pd.DataFrame(era5l_data['tas'])
pr_target = pd.DataFrame(era5l_data['pr'])
train_start_temp = str(tas_target.first_valid_index())
train_end_temp = str(tas_target.last_valid_index())
train_start_prec = str(pr_target.first_valid_index())
train_end_prec = str(pr_target.last_valid_index())
elif self.reanalysis == 'chelsa':
# Load CHELSA data
tas_target = pd.read_csv(f'{self.reanalysis_dir}{self.poly_name}_tas.csv', index_col='time', parse_dates=True)
pr_target = pd.read_csv(f'{self.reanalysis_dir}{self.poly_name}_pr.csv', index_col='time', parse_dates=True)
train_start_temp = str(tas_target.first_valid_index())
train_end_temp = str(tas_target.last_valid_index())
train_start_prec = str(pr_target.first_valid_index())
train_end_prec = str(pr_target.last_valid_index())
else:
raise ValueError("Unsupported reanalysis data source. Use 'era5l' or 'chelsa'.")
# Temperature bias adjustment
self.ssp2_tas, raw2_tas_train, adj2_tas_train = adjust_bias(
self.ssp2_tas_raw, tas_target, datasource=self.reanalysis,
train_start=train_start_temp, train_end=train_end_temp
)
self.ssp5_tas, raw5_tas_train, adj5_tas_train = adjust_bias(
self.ssp5_tas_raw, tas_target, datasource=self.reanalysis,
train_start=train_start_temp, train_end=train_end_temp
)
# Precipitation bias adjustment
self.ssp2_pr, raw2_pr_train, adj2_pr_train = adjust_bias(
self.ssp2_pr_raw, pr_target, datasource=self.reanalysis,
train_start=train_start_prec, train_end=train_end_prec
)
self.ssp5_pr, raw5_pr_train, adj5_pr_train = adjust_bias(
self.ssp5_pr_raw, pr_target, datasource=self.reanalysis,
train_start=train_start_prec, train_end=train_end_prec
)
# Main dictionaries for raw and adjusted CMIP6 data
self.ssp_tas_dict = {
'SSP2_raw': self.ssp2_tas_raw,
'SSP2_adjusted': self.ssp2_tas,
'SSP5_raw': self.ssp5_tas_raw,
'SSP5_adjusted': self.ssp5_tas
}
self.ssp_pr_dict = {
'SSP2_raw': self.ssp2_pr_raw,
'SSP2_adjusted': self.ssp2_pr,
'SSP5_raw': self.ssp5_pr_raw,
'SSP5_adjusted': self.ssp5_pr
}
# Dedicated training evaluation dictionary
self.training_dict = {
'tas': {
'SSP2_raw_train': raw2_tas_train,
'SSP2_adjusted_train': adj2_tas_train,
'SSP5_raw_train': raw5_tas_train,
'SSP5_adjusted_train': adj5_tas_train,
'reference': tas_target.loc[train_start_temp:train_end_temp]
},
'pr': {
'SSP2_raw_train': raw2_pr_train,
'SSP2_adjusted_train': adj2_pr_train,
'SSP5_raw_train': raw5_pr_train,
'SSP5_adjusted_train': adj5_pr_train,
'reference': pr_target.loc[train_start_prec:train_end_prec]
}
}
print('Done!')
def process_nested_dict(d, func, *args, **kwargs):
for key, value in d.items():
if isinstance(value, pd.DataFrame):
d[key] = func(value, *args, **kwargs)
elif isinstance(value, dict):
process_nested_dict(value, func, *args, **kwargs)
def dict_filter(dictionary, filter_string):
"""Returns a dict with all elements of the input dict that contain a filter string in their keys."""
return {key.split('_')[0]: value for key, value in dictionary.items() if filter_string in key}
class DataFilter:
def __init__(self, df, zscore_threshold=3, resampling_rate=None, prec=False, jump_threshold=5):
self.df = df
self.zscore_threshold = zscore_threshold
self.resampling_rate = resampling_rate
self.prec = prec
self.jump_threshold = jump_threshold
self.filter_all()
def check_outliers(self):
"""
A function for filtering a pandas dataframe for columns with obvious outliers
and dropping them based on a z-score threshold.
Returns
-------
models : list
A list of columns identified as having outliers.
"""
# Resample if rate specified
if self.resampling_rate is not None:
if self.prec:
self.df = self.df.resample(self.resampling_rate).sum()
else:
self.df = self.df.resample(self.resampling_rate).mean()
# Calculate z-scores for each column
z_scores = pd.DataFrame((self.df - self.df.mean()) / self.df.std())
# Identify columns with at least one outlier (|z-score| > threshold)
cols_with_outliers = z_scores.abs().apply(lambda x: any(x > self.zscore_threshold))
self.outliers = list(self.df.columns[cols_with_outliers])
# Return the list of columns with outliers
return self.outliers
def check_jumps(self):
"""
A function for checking a pandas dataframe for columns with sudden jumps or drops
and returning a list of the columns that have them.
Returns
-------
jumps : list
A list of columns identified as having sudden jumps or drops.
"""
cols = self.df.columns
jumps = []
for col in cols:
diff = self.df[col].diff()
if (abs(diff) > self.jump_threshold).any():
jumps.append(col)
self.jumps = jumps
return self.jumps
def filter_all(self):
"""
A function for filtering a dataframe for columns with obvious outliers
or sudden jumps or drops in temperature, and returning a list of the
columns that have been filtered using either or both methods.
Returns
-------
filtered_models : list
A list of columns identified as having outliers or sudden jumps/drops in temperature.
"""
self.check_outliers()
self.check_jumps()
self.filtered_models = list(set(self.outliers) | set(self.jumps))
return self.filtered_models
def loop_checks(ssp_dict, **kwargs):
"""
Wrapper for class DataFilter to iterate over all scenarios.
"""
outliers = []
jumps = []
both_checks = []
for scenario in ssp_dict.keys():
filter = DataFilter(ssp_dict[scenario], **kwargs)
outliers.extend(set(filter.outliers))
jumps.extend(set(filter.jumps))
both_checks.extend(set(filter.filtered_models))
return outliers, jumps, both_checks
def drop_model(col_names, dict_or_df):
"""
Drop columns with given names from either a dictionary of dataframes
or a single dataframe.
Parameters
----------
col_names : list of str
The list of model names to drop.
dict_or_df : dict of pandas.DataFrame or pandas.DataFrame
If a dict of dataframes, all dataframes in the dict will be edited.
If a single dataframe, only that dataframe will be edited.
Returns
-------
dict_of_dfs : dict of pandas.DataFrame or pandas.DataFrame
The updated dictionary of dataframes or dataframe with dropped columns.
"""
if isinstance(dict_or_df, dict):
# loop through the dictionary and edit each dataframe
for key in dict_or_df.keys():
if all(col_name in dict_or_df[key].columns for col_name in col_names):
dict_or_df[key] = dict_or_df[key].drop(columns=col_names)
return dict_or_df
elif isinstance(dict_or_df, pd.DataFrame):
# edit the single dataframe
if all(col_name in dict_or_df.columns for col_name in col_names):
return dict_or_df.drop(columns=col_names)
else:
raise TypeError('Input must be a dictionary or a dataframe')
def apply_filters(temp_dict, prec_dict, **kwargs):
"""
Applies data filters to temperature and precipitation dictionaries.
Parameters
----------
temp_dict : dict
Dictionary containing temperature data.
prec_dict : dict
Dictionary containing precipitation data.
**kwargs
Additional keyword arguments for loop_checks function.
Returns
-------
tuple of pandas.DataFrame
Tuple containing filtered temperature and precipitation data.
"""
tas_raw = dict_filter(temp_dict, 'raw')
outliers, jumps, both_checks = loop_checks(tas_raw, **kwargs)
print('Applying data filters...')
print('Models with temperature outliers: ' + str(outliers))
print('Models with temperature jumps: ' + str(jumps))
print('Models excluded: ' + str(both_checks))
return drop_model(both_checks, temp_dict), drop_model(both_checks, prec_dict)
def pickle_to_dict(file_path):
"""
Loads a dictionary from a pickle file at a specified file path.
Parameters
----------
file_path : str
The path of the pickle file to load.
Returns
-------
dict
The dictionary loaded from the pickle file.
"""
with open(file_path, 'rb') as f:
dic = pickle.load(f)
return dic
def dict_to_pickle(dic, target_path):
"""
Saves a dictionary to a pickle file at the specified target path.
Creates target directory if not existing.
Parameters
----------
dic : dict
The dictionary to save to a pickle file.
target_path : str
The path of the file where the dictionary shall be stored.
Returns
-------
None
"""
target_dir = os.path.dirname(target_path)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with open(target_path, 'wb') as f:
pickle.dump(dic, f)
def cmip_plot(ax, df, target, title=None, precip=False, intv_sum='ME', intv_mean='10Y',
target_label='Target', show_target_label=False, rolling=None):
"""Resamples and plots climate model and target data."""
if intv_mean == '10Y' or intv_mean == '5Y' or intv_mean == '20Y':
closure = 'left'
else:
closure = 'right'
if not precip:
if rolling is not None:
ax.plot(df.resample(intv_mean, closed=closure, label='left').mean().iloc[:, :].rolling(rolling).mean(), linewidth=1.2)
else:
ax.plot(df.resample(intv_mean, closed=closure, label='left').mean().iloc[:, :], linewidth=1.2)
era_plot, = ax.plot(target['tas'].resample(intv_mean).mean(), linewidth=1.5, c='red', label=target_label,
linestyle='dashed')
else:
if rolling is not None:
ax.plot(df.resample(intv_sum, closed=closure, label='left').sum().iloc[:, :].rolling(rolling).mean(), linewidth=1.2)
else:
ax.plot(df.resample(intv_sum, closed=closure, label='left').sum().iloc[:, :], linewidth=1.2)
era_plot, = ax.plot(target['pr'].resample(intv_sum).sum(), linewidth=1.5,
c='red', label=target_label, linestyle='dashed')
if show_target_label:
ax.legend(handles=[era_plot], loc='upper left')
ax.set_title(title)
ax.grid(True)
def cmip_plot_combined(data, target, title=None, precip=False, intv_sum='ME', intv_mean='10Y',
target_label='Target', show=False, filename=None, out_dir='./', rolling=None):
"""Combines multiple subplots of climate data in different scenarios before and after bias adjustment.
Shows target data for comparison"""
figure, axis = plt.subplots(2, 2, figsize=(12, 12), sharex="col", sharey="all")
t_kwargs = {'target': target, 'intv_mean': intv_mean, 'target_label': target_label, 'rolling': rolling}
p_kwargs = {'target': target, 'intv_mean': intv_mean, 'target_label': target_label,
'intv_sum': intv_sum, 'precip': True, 'rolling': rolling}
if not os.path.exists(out_dir):
os.makedirs(out_dir)
if not precip:
cmip_plot(axis[0, 0], data['SSP2_raw'], show_target_label=True, title='SSP2 raw', **t_kwargs)
cmip_plot(axis[0, 1], data['SSP2_adjusted'], title='SSP2 adjusted', **t_kwargs)
cmip_plot(axis[1, 0], data['SSP5_raw'], title='SSP5 raw', **t_kwargs)
cmip_plot(axis[1, 1], data['SSP5_adjusted'], title='SSP5 adjusted', **t_kwargs)
figure.legend(data['SSP5_adjusted'].columns, loc='lower right', ncol=6, mode="expand")
figure.tight_layout()
figure.subplots_adjust(bottom=0.15, top=0.92)
figure.suptitle(title, fontweight='bold')
plt.savefig(out_dir + filename)
if show:
plt.show()
else:
cmip_plot(axis[0, 0], data['SSP2_raw'], show_target_label=True, title='SSP2 raw', **p_kwargs)
cmip_plot(axis[0, 1], data['SSP2_adjusted'], title='SSP2 adjusted', **p_kwargs)
cmip_plot(axis[1, 0], data['SSP5_raw'], title='SSP5 raw', **p_kwargs)
cmip_plot(axis[1, 1], data['SSP5_adjusted'], title='SSP5 adjusted', **p_kwargs)
figure.legend(data['SSP5_adjusted'].columns, loc='lower right', ncol=6, mode="expand")
figure.tight_layout()
figure.subplots_adjust(bottom=0.15, top=0.92)
figure.suptitle(title, fontweight='bold')
plt.savefig(out_dir + filename)
if show:
plt.show()
def df2long(df, intv_sum='ME', intv_mean='YE', precip=False):
"""Resamples dataframes and converts them into long format to be passed to seaborn.lineplot()."""
if precip:
df = df.resample(intv_sum).sum()
df = df.reset_index()
df = df.melt('TIMESTAMP', var_name='model', value_name='prec')
else:
df = df.resample(intv_mean).mean()
df = df.reset_index()
df = df.melt('TIMESTAMP', var_name='model', value_name='temp')
return df
def cmip_plot_ensemble(cmip, target, precip=False, intv_sum='ME', intv_mean='YE', figsize=(10, 6), site_label:str=None,
target_label='ERA5L', show=True, out_dir='./', filename='cmip6_ensemble'):
"""
Plots the multi-model mean of climate scenarios including the 90% confidence interval.
Parameters
----------
cmip: dict
A dictionary with keys representing the different CMIP6 models and scenarios as pandas dataframes
containing data of temperature and/or precipitation.
target: pandas.DataFrame
Dataframe containing the historical reanalysis data.
precip: bool
If True, plot the mean precipitation. If False, plot the mean temperature. Default is False.
intv_sum: str
Interval for precipitation sums. Default is monthly ('ME').
intv_mean: str
Interval for the mean of temperature data or precipitation sums. Default is annual ('YE').
figsize: tuple
Figure size for the plot. Default is (10,6).
show: bool
If True, show the resulting plot. If False, do not show it. Default is True.
out_dir: str
Target directory to save figure
"""
warnings.filterwarnings(action='ignore')
figure, axis = plt.subplots(figsize=figsize)
# Define color palette
colors = ['darkorange', 'orange', 'darkblue', 'dodgerblue']
# create a new dictionary with the same keys but new values from the list
col_dict = {key: value for key, value in zip(cmip.keys(), colors)}
if site_label is None:
site_label = str()
else:
site_label = f'"{site_label}" - '
if precip:
for i in cmip.keys():
df = df2long(cmip[i], intv_sum=intv_sum, intv_mean=intv_mean, precip=True)
sns.lineplot(data=df, x='TIMESTAMP', y='prec', color=col_dict[i])
axis.set(xlabel='Year', ylabel='Precipitation [mm]')
if intv_sum == 'ME':
figure.suptitle(site_label + 'Ensemble Mean of Monthly Precipitation', fontweight='bold')
elif intv_sum == 'YE':
figure.suptitle(site_label + 'Ensemble Mean of Annual Precipitation', fontweight='bold')
target_plot = axis.plot(target.resample(intv_sum).sum(), linewidth=1.5, c='black',
label=target_label, linestyle='dashed')
else:
for i in cmip.keys():
df = df2long(cmip[i], intv_mean=intv_mean)
sns.lineplot(data=df, x='TIMESTAMP', y='temp', color=col_dict[i])
axis.set(xlabel='Year', ylabel='Air Temperature [K]')
if intv_mean == '10Y':
figure.suptitle(site_label + 'Ensemble Mean of 10y Air Temperature', fontweight='bold')
elif intv_mean == 'YE':
figure.suptitle(site_label + 'Ensemble Mean of Annual Air Temperature', fontweight='bold')
elif intv_mean == 'ME':
figure.suptitle(site_label + 'Ensemble Mean of Monthly Air Temperature', fontweight='bold')
target_plot = axis.plot(target.resample(intv_mean).mean(), linewidth=1.5, c='black',
label=target_label, linestyle='dashed')
axis.legend(['SSP2_raw', '_ci1', 'SSP2_adjusted', '_ci2', 'SSP5_raw', '_ci3', 'SSP5_adjusted', '_ci4'],
loc="upper center", bbox_to_anchor=(0.43, -0.15), ncol=4,
frameon=False) # First legend --> Workaround as seaborn lists CIs in legend
leg = Legend(axis, target_plot, [target_label], loc='upper center', bbox_to_anchor=(0.83, -0.15), ncol=1,
frameon=False) # Second legend (Target)
axis.add_artist(leg)
plt.grid()
figure.tight_layout(rect=[0, 0.02, 1, 1]) # Make some room at the bottom
if not precip:
plt.savefig(out_dir + f'{filename}_temperature.png')
else:
plt.savefig(out_dir + f'{filename}_precipitation.png')
if show:
plt.show()
warnings.filterwarnings(action='always')
def prob_plot(original, target, corrected, ax, title=None, ylabel="Temperature [K]", **kwargs):
"""
Combines probability plots of climate model data before and after bias adjustment
and the target data.
Parameters
----------
original : pandas.DataFrame
The original climate model data.
target : pandas.DataFrame
The target data.
corrected : pandas.DataFrame
The climate model data after bias adjustment.
ax : matplotlib.axes.Axes
The axes on which to plot the probability plot.
title : str, optional
The title of the plot. Default is None.
ylabel : str, optional
The label for the y-axis. Default is "Temperature [K]".
**kwargs : dict, optional
Additional keyword arguments passed to the probscale.probplot() function.
Returns
-------
fig : matplotlib Figure
The generated figure.
"""
scatter_kws = dict(label="", marker=None, linestyle="-")
common_opts = dict(plottype="qq", problabel="", datalabel="", **kwargs)
scatter_kws["label"] = "original"
fig = probscale.probplot(original, ax=ax, scatter_kws=scatter_kws, **common_opts)
scatter_kws["label"] = "target"
fig = probscale.probplot(target, ax=ax, scatter_kws=scatter_kws, **common_opts)
scatter_kws["label"] = "adjusted"
fig = probscale.probplot(corrected, ax=ax, scatter_kws=scatter_kws, **common_opts)
ax.set_title(title)
ax.set_xlabel("Standard Normal Quantiles")
ax.set_ylabel(ylabel)
ax.grid(True)
score = round(target.corr(corrected), 2)
ax.text(0.05, 0.8, f"R² = {score}", transform=ax.transAxes, fontsize=15)
return fig
def pp_matrix(original, target, corrected, scenario=None, nrow=7, ncol=5, precip=False,
starty=1979, endy=2022, show=False, out_dir='./', target_label='ERA5-Land', site:str=None):
"""
Arranges the prob_plots of all CMIP6 models in a matrix and adds the R² score.
Parameters
----------
original : pandas.DataFrame
The original climate model data.
target : pandas.DataFrame
The target data.
corrected : pandas.DataFrame
The climate model data after bias adjustment.
scenario : str, optional
The climate scenario to be added to the plot title.
nrow : int, optional
The number of rows in the plot matrix. Default is 7.
ncol : int, optional
The number of columns in the plot matrix. Default is 5.
precip : bool, optional
Indicates whether the data is precipitation data. Default is False.
show : bool, optional
Indicates whether to display the plot. Default is False.
out_dir: str
Target directory to save figure
Returns
-------
None
"""
starty = f'{str(starty)}-01-01'
endy = f'{str(endy)}-12-31'
period = slice(starty, endy)
if site is None:
site_label = str()
else:
site_label = f'"{site}" - '
if precip:
var = 'Precipitation'
var_label = 'Monthly ' + var
unit = ' [mm]'
original = original.resample('ME').sum()
target = target.resample('ME').sum()