-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrdc_monthly5d.py
More file actions
executable file
·1837 lines (1620 loc) · 77.4 KB
/
Copy pathgrdc_monthly5d.py
File metadata and controls
executable file
·1837 lines (1620 loc) · 77.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#author: alex sun
#date: 0824
#find good grdc reference data
#Daily runoff data downloaded by using Download Station, selected such that drainage area>4e4 km2
#date: 0826, cleaned up for production. Use plotglobalmap and itask=2 for global
#rev date: 09072022, double check for grace monthly meeting
#rev date: 06092023, cleanup for manuscript
#rev date: 06232023, add plots for bivariate, joint occurrence, and CMI
#For bivariate, CMI vs. Joint Occurrence; for joint occurrence it's P and TWS; and CMI it's (TWS, Q|P)
#rev date: 07312023, consider remove season option, this is enabled by setting cfg.data.deseason to true
#rev date: 08012023, change to use fake 5d data generated from monthly solutions
#rev date: 08022023, cleanup and add annotations
#rev date: 08052023, implemented SWE removal to use SWE, set cfg.data.removeSWE to True
#rev date: 08072023, fixed bug in doSWERemoval, should use anomaly by subtracting mean SWE
#rev date: 09192023, added yangtze river data
#rev date: 10312023, fixed bug in compound_events_monthly related to dates. Now the fake5d dates are
# enforced to be the same as csr5d dates
#rev date: 03292024, plot diff between 5d and monthly
#=======================================================================================================
import pandas as pd
import os
os.environ['USE_PYGEOS'] = '0'
import geopandas as gpd
import xarray as xr
import rioxarray
import matplotlib.pyplot as plt
import numpy as np
import pickle as pkl
import sys
import cartopy.crs as ccrs
import hydrostats as HydroStats
import colorcet as cc
from datetime import datetime
from scipy.stats import kendalltau, gumbel_r
from sklearn.preprocessing import PowerTransformer
from sklearn.linear_model import LinearRegression
from mpl_toolkits.axes_grid1 import make_axes_locatable
import cartopy.crs as ccrs
from shapely.geometry import Point
from matplotlib.colors import ListedColormap
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
from scipy.stats import pearsonr
from generativepy.color import Color
from matplotlib.colors import rgb2hex
import rioxarray as rxr
import matplotlib
import seaborn as sns
from tigramite.independence_tests.parcorr import ParCorr
from tigramite.independence_tests.robust_parcorr import RobustParCorr
from tigramite.independence_tests.cmiknn import CMIknn
from tigramite.independence_tests.cmisymb import CMIsymb
from tigramite.independence_tests.regressionCI import RegressionCI
from tigramite.independence_tests.gsquared import Gsquared
from tigramite import data_processing as pp
from tigramite import plotting as tp
from tigramite.pcmci import PCMCI
from tigramite.causal_effects import CausalEffects
from tigramite.models import LinearMediation
from myutils import getRegionExtent, getFPIData
from dataloader_global import load5ddatasets,loadClimatedatasets,getCSR5dLikeArray
import glofas_us
from glofas_us import extractBasinOutletQ, loadGLOFAS4CONUS
from myutils import bandpass_filter,removeClimatology
from csr_monthly_dataloader import convertMonthlyTo5d, loadFake5ddatasets,loadFake5ddatasetsNoSWE
from myutils import genColorList
import warnings
warnings.filterwarnings("ignore")
#dictionary for plotting
regionNames = {
'north_america': "North America",
"south_america": "South America",
"europe": "Europe",
"africa": "Africa",
"south_pacific": "South-West Pacific",
"global": '' }
hydroshedMaps={
"north_america": 'hybas_na_lev04_v1c/hybas_na_lev04_v1c.shp',
'south_america': 'hybas_sa_lev04_v1c/hybas_sa_lev04_v1c.shp',
'europe': 'hybas_eu_lev04_v1c/hybas_eu_lev04_v1c.shp',
'africa': 'hybas_af_lev04_v1c/hybas_af_lev04_v1c.shp',
'south_pacific': "hybas_au_lev04_v1c/hybas_au_lev04_v1c.shp"
}
#number of neighbors
KNN = 6
#BASIN AREA
MIN_BASIN_AREA = 1.2e5 #[km2]
def getExtremeEvents(series, method='MAF', cutoff=90, transform=False, minDist=None,
season=None, returnExtremeSeries=False):
"""
method: MAF, mean annual flood; POT peak over threshold
"""
#from pyextremes import EVA
#transform Q to normal space
if transform:
val = PowerTransformer().fit_transform(series.to_numpy()[:,np.newaxis]).squeeze()
series = pd.Series(val, index=series.index)
if method == 'MAF':
#extremes = series.groupby(series.index.year).agg(['idxmax', 'max'])
#extremes = pd.Series(extremes['max'].values, index=extremes['idxmax'])
#asun0711, enforce minimum distance between events
nEvent = 5
extremes = series.groupby(series.index.year).nlargest(nEvent)
extremes = extremes.reset_index(level=[0,1]) #flatten the multi-index
extremes = pd.Series(extremes[0].values, index=extremes['level_1'])
#check the distance between events
if not minDist is None:
#remove close events
nYears = len(series.index.year.unique())
goodInd = [0]
counter = 0
for i in range(1, nYears):
#loop through the n largest events in each year
#if the distance between two adjacent events is smaller than minDist, record the event index
for j in range(nEvent):
if np.abs(extremes.index[i*nEvent+j] - extremes.index[goodInd[counter]]).days>minDist:
goodInd.append(i*nEvent+j)
counter+=1
break
elif j==nEvent-1:
#this should not be reached
raise ValueError('cannot find events ')
extremes = extremes.iloc[goodInd]
elif method == 'POT':
#POT
thresh = np.nanpercentile(series.to_numpy(), cutoff)
extremes = series.loc[series>=thresh]
extremes = extremes.sort_values(ascending=False)
if not minDist is None:
#remove close events
goodInd = [0]
#the following double loop ensures the higher magnitude events are always selected over lower-magnitude adjacent events
for i in range(1, extremes.shape[0]):
flag=False
for j in range(0, i):
if np.abs((extremes.index[i] - extremes.index[j]).days)<minDist:
flag=True
if not flag:
goodInd.append(j)
extremes = extremes.iloc[goodInd]
if not season is None:
#note season is zero-based
if season == 'DJF':
monrng = [11,0,1]
elif season == 'MAM':
monrng = [2,3,4]
elif season == 'JJA':
monrng = [5,6,7]
elif season == 'SON':
monrng = [8,9,10]
elif season == 'MAMJJA':
monrng = [2,3,4,5,6,7]
elif season == 'AMJJAS':
monrng = [3,4,5,6,7,8]
else:
raise ValueError("wrong season code")
extremes = extremes[extremes.index.month.isin(monrng)]
print ('POT: num events extracted', len(extremes), '@ cutoff', cutoff, 'for season', season)
else:
print ('POT: num events extracted', len(extremes), '@ cutoff', cutoff)
print ('*'*80)
else:
raise ValueError("invalid method")
events = np.zeros((series.size),dtype=int)
#drop bad data
extremes = extremes.dropna()
#is there a better way?
for ix, item in enumerate(series.index.tolist()):
for iy, time2 in enumerate(extremes.index.tolist()):
if (item==time2):
events[ix] = 1
if len(np.where(events==1)[0]) != extremes.size:
print ("warning:", len(np.where(events==1)[0]), extremes.size)
#check all events are accounted for
#assert(len(np.where(events==1)[0]) == extremes.size)
if returnExtremeSeries:
return events, extremes
else:
return events
def getBasinMask(stationID, region='north_america', gdf=None):
""" Get basin mask as a geopandas DF
Param
-----
stationID, grdc_no
region, one of the valid regions
gdf, if not None, it contains the combined GDF for all stations a region
This is downloaded from GRDC as part of the station manual selection
Returns
-------
basin_gdf, gdf of the basin
"""
rootdir = '/home/suna/work/grace/data/grdc'
if region == 'globalref':
shpfile = os.path.join(rootdir, f'grdc_basins_smoothed_md_no_{stationID}.shp')
basin_gdf = gpd.read_file(shpfile)
return basin_gdf
else:
#suppress the SettingWithCopyWarning warning
basin_gdf = gdf.loc[ gdf['grdc_no']==stationID].copy(deep=True)
return basin_gdf
def getPredictor4Basin(gdf,lat,lon, xds):
"""Crop the global dataset for the specified basin
Params
------
gdf, mask of the basin
xds, DataArray of the dataset to be masked
Returns
-------
meanTS, the basin average time series (1D dataarray)
"""
xds.rio.set_spatial_dims(x_dim="lon", y_dim="lat", inplace=True)
xds.rio.write_crs("epsg:4326", inplace=True)
#must rename coords for rioarray to work
xds = xds.rename({'lat':'y', 'lon':'x'})
xds = xds.sortby('y')
try:
with rioxarray.set_options(export_grid_mapping=False):
bbox=gdf.bounds
#convert to [lon0,lat0,lon1,lat1]
bbox=bbox.values.tolist()[0]
basinxds = xds.sel(y=slice(bbox[1],bbox[3]),x=slice(bbox[0],bbox[2]))
#08/28, add all_touched = True
clipped = basinxds.rio.clip(gdf.geometry, gdf.crs, from_disk=True, drop=True, invert=False, all_touched = True)
meanTS = clipped.where(clipped.notnull()).mean(dim=['y','x'])
except:
#get 3x3 region around station cell if the above process fails
cellDA = xds.sel(y=slice(lat-1.5, lat+1.5), x=slice(lon-1.5, lon+1.5))
print ('number of cells', cellDA.shape[1])
meanTS = cellDA.where(cellDA.notnull()).mean(dim=['y','x'])
return meanTS
def getBasinData(config, stationID, region, lat, lon, xds = None,
xds_Precip=None, gdf=None, returnFPI=False,xdsC = None, removeSWE=False):
"""Get basin-averaged time series
Params
------
stationID, grdc station id
region, geo region
lat,lon, location of the station
xds, CSR.5d
xds_Precip, precip data
"""
gdf = getBasinMask(stationID=stationID, region=region, gdf=gdf)
region = getRegionExtent(regionName="global")
#TWS
#07142023: use TWS 0.25 for masking, but ERA5 1deg for masking
# ERA5 0.25 deg is too big to load into memory
#Do this in two steps.
# Step 1: turn coarsen in load5ddatasets to True, reload to True in both loadFake5ddatasetsNoSWE and loadClimatedatasets=>1deg data
# comment out da = da.interp(coords={'lat':daCSR0.lat, 'lon':daCSR0.lon, 'time':da.time}, method='nearest') in csr_monthly_dataloader.py
# Step 2: turn coarsen to False, reload to True in loadFake5ddatasetsNoSWE,
# uncomment da = da.interp(coords={'lat':daCSR0.lat, 'lon':daCSR0.lon, 'time':da.time}, method='nearest') in csr_monthly_dataloader.py
# but False in loadClimatedatasets => 0.25 deg data
if xds is None:
if not removeSWE:
print ('!!! Load original TWS')
xds,_, _ = loadFake5ddatasets(cfg=config,
region=region,
coarsen=False,
mask_ocean=config.data.mask_ocean,
startYear=datetime.strptime(config.data.start_date, '%Y/%m/%d').date().year,
endYear=datetime.strptime(config.data.end_date, '%Y/%m/%d').date().year
)
else:
print ('!!! load TWS w/ SWE removal')
xds = loadFake5ddatasetsNoSWE(cfg=config,
region=region,
coarsen=True, #change this to false and comment out 0.25 in csr_monthly_dataloader.py
reLoad=config.monthly.reload,
mask_ocean=config.data.mask_ocean,
startYear=datetime.strptime(config.data.start_date, '%Y/%m/%d').date().year,
endYear=datetime.strptime(config.data.end_date, '%Y/%m/%d').date().year
)
print ('loaded tws array shape', xds.shape)
basinTWS = getPredictor4Basin(gdf, lat, lon, xds)
#Precip [use saved 5d data]
if xds_Precip is None:
xds_Precip = loadClimatedatasets(region, vartype='precip', daCSR5d= xds, \
aggregate5d=True,
reLoad= config.data.reload_precip,
precipSource=config.data.precip_source,
startYear= datetime.strptime(config.data.start_date, '%Y/%m/%d').date().year,
endYear=datetime.strptime(config.data.end_date, '%Y/%m/%d').date().year,
fake5d=True)
basinP = getPredictor4Basin(gdf, lat, lon, xds_Precip)
return basinTWS, basinP, xds, xds_Precip
def readStationSeries(stationID, region='north_america'):
""" Parse GRDC runoff time series
Note: the null values are dropped at this stage
Params
------
stationID: id of the GRDC station
"""
rootdir = f'/home/suna/work/grace/data/grdc/{region}'
stationfile = os.path.join(rootdir, f'{stationID}_Q_Day.Cmd.txt')
#skip 37 header rows
df = pd.read_csv(stationfile, encoding = 'unicode_escape', skiprows=37, index_col=0, delimiter=';', usecols=[0, 2], header=None)
df.columns=['Q']
df.index = pd.to_datetime(df.index)
df.index.names = ['time']
#drop bad values
df= df[df.Q>0]
return df
def print_significant_links(N, var_names,
p_matrix,
val_matrix,
conf_matrix=None,
graph=None,
ambiguous_triples=None,
alpha_level=0.05):
"""Prints significant links.
#asun: this is copied/modified from github pcmci.py
Used for output of PCMCI and PCMCIplus. For the latter also information
on ambiguous links and conflicts is returned.
Parameters
----------
alpha_level : float, optional (default: 0.05)
Significance level.
p_matrix : array-like
Must be of shape (N, N, tau_max + 1).
val_matrix : array-like
Must be of shape (N, N, tau_max + 1).
conf_matrix : array-like, optional (default: None)
Matrix of confidence intervals of shape (N, N, tau_max+1, 2).
graph : array-like
Must be of shape (N, N, tau_max + 1).
ambiguous_triples : list
List of ambiguous triples.
"""
if graph is not None:
sig_links = (graph != "")*(graph != "<--")
else:
sig_links = (p_matrix <= alpha_level)
print("\n## Significant links at alpha = %s:" % alpha_level)
for j in range(N):
links = {(p[0], -p[1]): np.abs(val_matrix[p[0], j, abs(p[1])])
for p in zip(*np.where(sig_links[:, j, :]))}
# Sort by value
sorted_links = sorted(links, key=links.get, reverse=True)
#return sorted_links for Q only [asun: 07042023]
if j == 0:
sorted_links_Q = sorted_links
n_links = len(links)
string = ("\n Variable %s has %d "
"link(s):" % (var_names[j], n_links))
for p in sorted_links:
string += ("\n (%s % d): pval = %.5f" %
(var_names[p[0]], p[1],
p_matrix[p[0], j, abs(p[1])]))
string += " | val = % .3f" % (
val_matrix[p[0], j, abs(p[1])])
if conf_matrix is not None:
string += " | conf = (%.3f, %.3f)" % (
conf_matrix[p[0], j, abs(p[1])][0],
conf_matrix[p[0], j, abs(p[1])][1])
if graph is not None:
if p[1] == 0 and graph[j, p[0], 0] == "o-o":
string += " | unoriented link"
if graph[p[0], j, abs(p[1])] == "x-x":
string += " | unclear orientation due to conflict"
return string, sorted_links_Q
def getCMI(cfg, stationID, df, river=None, saveDataFrame=False):
"""Get conditional MI
I(X; Y | Z) = I(X; Y, Z) - I(X; Z)
The conditional mutual information is a measure of how much uncertainty is shared by X and
Y , but not by Z.
Params
------
stationID, id of the station
df, dataframe containing all variables
"""
plotting = cfg.data.plot_bivarate_scatter
# CMI(X,Y|Z)
# X = group 0; Y= group 1; Z = group 2
# 0 1 2
#[Q, TWS, P]
var_names=df.columns
data = df.values
dataframe = pp.DataFrame(data,
datatime = {0:np.arange(data.shape[0])},
var_names=var_names,
missing_flag=-999.)
#Calculate CMI
#parcorr = ParCorr(significance='analytic')
pcmci = PCMCI(
dataframe=dataframe,
cond_ind_test=RobustParCorr(), #parcorr,
verbosity=1)
correlations = pcmci.get_lagged_dependencies(tau_min=cfg.causal.tau_min, tau_max=cfg.causal.tau_max, val_only=True)['val_matrix']
if plotting:
plt.figure()
matrix_lags = np.argmax(np.abs(correlations), axis=2)
tp.plot_densityplots(dataframe=dataframe, setup_args={'figsize':(15, 10)}, add_densityplot_args={'matrix_lags':matrix_lags});
#tp.plot_densityplots(dataframe=dataframe, add_densityplot_args={'matrix_lags':None})
plt.savefig(f'outputs/test_density_plot{stationID}.png')
plt.close()
plt.figure()
tp.plot_scatterplots(dataframe=dataframe,
setup_args={'figsize': (16,16), 'label_fontsize': 16},
add_scatterplot_args={'matrix_lags':matrix_lags, 'color': 'blue', 'markersize':10, 'alpha':0.7})
plt.savefig(f"outputs/test_scatterplot{stationID}.png")
plt.close()
plt.figure()
tp.plot_timeseries(dataframe);
plt.savefig(f"outputs/test_timeseries{stationID}.png")
plt.close()
if saveDataFrame:
#save dataframe for later use
pkl.dump(dataframe, open(f'grdcdataframes/s_{stationID}.pkl', 'wb'))
cmi_knn = CMIknn(
significance='shuffle_test',
knn=10, #if <1, this is fraction of all samples
shuffle_neighbors= 10,
workers = 12,
transform='rank',
sig_samples=1000,
verbosity=0)
arr = data.T
# Subsample indices
# x_indices = np.where(xyz == 0)[0]
# y_indices = np.where(xyz == 1)[0]
# z_indices = np.where(xyz == 2)[0]
# index groups 0: X; 1: Y; 2: Z (all index groups may have multiple variables )
#note: tigramite requires array to have X, Y, Z in rows and observations in columns
xyz = np.array([0, 1, 2],dtype=int)
cmi_knn_score = cmi_knn.get_dependence_measure(arr, xyz=xyz)
#p_val = cmi_knn.get_shuffle_significance(arr, xyz=xyz, value=cmi_knn_score)
# if plotting:
# fig,ax=plt.subplots(1,1)
# matrix = tp.plot_lagfuncs(val_matrix=correlations,
# setup_args={'var_names':var_names, 'x_base':5, 'y_base':.5})
# matrix.fig.suptitle(f'{river}, CMI:{cmi_knn_score:4.3f}', fontsize=10,color='red')
# plt.savefig(f'test_lag_plot_{stationID}.png')
# plt.close()
# if plotting:
# fig,ax = plt.subplots(2,1)
# tp.plot_timeseries(dataframe, fig_axes=(fig,ax[0]))
# ax[0].set_title(f'GRDC No. {stationID}')
# tp.plot_graph(
# val_matrix=results['val_matrix'],
# graph=results['graph'],
# var_names=var_names,
# link_colorbar_label='cross-MCI',
# node_colorbar_label='auto-MCI',
# vmin_edges=0.,
# vmax_edges = 0.3,
# edge_ticks=0.05,
# cmap_edges='OrRd',
# vmin_nodes=0,
# vmax_nodes=.5,
# node_ticks=.1,
# cmap_nodes='OrRd',
# fig_ax = ax[1],
# )
# plt.savefig(f'testcmi_{stationID}.png')
# plt.close()
return cmi_knn_score
def doCausalAnalytics(cfg, df, binary=False):
"""
do causal analytics
06202023
see
https://github.com/jakobrunge/tigramite/blob/master/tutorials/case_studies/climate_case_study.ipynb
"""
#assumption: target variable Q is always the first!!!
# 0 1 2
#[Q, TWS, P]
var_names=df.columns
data = df.values
dataframe = pp.DataFrame(data,
datatime = df.index.values,
var_names=var_names,
missing_flag=-999)
tau_min = cfg.causal.tau_min
tau_max = cfg.causal.tau_max
#formulate links
selected_links = {}
# link_assumptions[j] = {(i, -tau):"-?>" for i in range(self.N) for tau in range(1, tau_max+1)}
for i in range(len(var_names)):
selected_links[i] = {}
ivar=0
for jvar in range(len(var_names)):
for ilag in range(tau_min, tau_max+1):
#exclude Q
if cfg.causal.exclude_Q:
if (jvar != 0):
selected_links[ivar][(jvar, -ilag)]='-?>'
else:
selected_links[ivar][(jvar, -ilag)]='-?>'
pc_alpha = 0.1
if binary:
cmi_symb = CMIsymb(significance='shuffle_test', n_symbs=None) #this is too slow
gsquared = Gsquared(significance='analytic')
pcmci_cmi_symb = PCMCI( dataframe=dataframe, cond_ind_test=gsquared)
results = pcmci_cmi_symb.run_pcmci(link_assumptions=selected_links,
tau_min = tau_min, tau_max=tau_max,
pc_alpha=pc_alpha)
#see ref at: https://github.com/jakobrunge/tigramite/blob/master/tutorials/causal_discovery/tigramite_tutorial_conditional_independence_tests.ipynb
#CMI = G/(2*n_samples)
outstr, sorted_links = print_significant_links(data.shape[1], var_names,
p_matrix=results['p_matrix'],
val_matrix=results['val_matrix']/(2.*df.shape[0]),
alpha_level=0.05)
med = LinearMediation(dataframe=dataframe)
med.fit_model(all_parents=pcmci_cmi_symb.all_parents, tau_max=tau_max)
med.fit_model_bootstrap(boot_blocklength=1, seed=28, boot_samples=200)
print (pcmci_cmi_symb.all_parents)
ace = med.get_all_ace()
ce_boots = med.get_bootstrap_of(function='get_all_ace', function_args={}, conf_lev=0.9)
print ("average causal effect of TWS,P ", ace )
print (ce_boots)
else:
pcmci = PCMCI(
dataframe=dataframe,
cond_ind_test= RobustParCorr() #cmi_knn,
)
results = pcmci.run_pcmci(
link_assumptions= selected_links,
tau_min=tau_min,
tau_max=tau_max, pc_alpha=pc_alpha)
outstr, sorted_links = print_significant_links(data.shape[1], var_names,
p_matrix=results['p_matrix'],
val_matrix=results['val_matrix'],
alpha_level=0.05)
Y = [(0,0)]
X = [(1,tau) for tau in range(-1,-tau_max,-1)]
S = [(2,tau) for tau in range(-1, -tau_max, -1)]
med = LinearMediation(dataframe=dataframe)
med.fit_model(all_parents=pcmci.all_parents, tau_max=tau_max)
med.fit_model_bootstrap(boot_blocklength=1, seed=28, boot_samples=200)
ace = med.get_all_ace()
ce_boots = med.get_bootstrap_of(function='get_all_ace', function_args={}, conf_lev=0.9)
print ("average causal effect of TWS,P ", ace)
print (ce_boots)
return outstr, sorted_links, results['p_matrix'],results['val_matrix'],ace,ce_boots
def fitScatterPlot(cfg, stationID, daTWS,daQ, river):
#
tws = daTWS.values
Q = daQ.values
timestamp =daTWS.time.values
tws_events = getExtremeEvents(pd.Series(tws.squeeze(), index=timestamp), method='MAF', cutoff=90, transform=False, minDist=cfg.event.t_win,
season=None, returnExtremeSeries=False)
q_events = getExtremeEvents(pd.Series(Q.squeeze(), index=timestamp), method='MAF', cutoff=90, transform=False, minDist=cfg.event.t_win,
season=None, returnExtremeSeries=False)
assert (len(tws_events) == len(timestamp))
#define quandrants of scatter plot
groups={'I':[], 'II':[], 'III':[], "IV":[]}
for count, (ix, iy) in enumerate(zip(tws_events, q_events)):
if ix == 0 and iy == 0:
groups['I'].append([tws[count], Q[count]])
elif ix == 0 and iy==1 :
groups['II'].append([tws[count], Q[count]])
elif ix==1 and iy==0:
groups['III'].append([tws[count], Q[count]])
else:
groups['IV'].append([tws[count], Q[count]])
plt.figure(figsize=(6,6))
for key in groups.keys():
groups[key] = np.array(groups[key])
if key == 'I':
symbolcolor='gray'
marker = 'o'
alpha = 0.7
markersize = 4
label = 'I'
elif key == 'II':
symbolcolor='#0484bc'
marker = 'o'
alpha = 1
markersize = 6
label = 'II (Q)'
elif key == 'III':
symbolcolor='#239B56'
marker = 'o'
alpha = 1
markersize = 6
label = 'III (TWS)'
else:
symbolcolor='#af0f2b'
marker = '*'
alpha = 1
markersize = 10
label = 'IV (Q^TWS)'
if not groups[key].size == 0:
plt.plot(groups[key][:,0], groups[key][:,1], linestyle = 'None', color=symbolcolor, markersize=markersize, marker=marker, alpha=alpha, label=label)
plt.xlabel('TWS [cm]')
plt.ylabel('Q [m/(km^2 s]')
plt.title(f'Station {stationID}, {river}')
plt.legend(loc='best')
if not cfg.data.deseason:
plt.savefig(f'outputs/fake5d_scatter_raw_{stationID}_{cfg.event.t_win}.png')
else:
plt.savefig(f'outputs/noseason_fake5d_scatter_raw_{stationID}_{cfg.event.t_win}.png')
plt.close()
def calculateMetrics(cfg, stationID, varDict, onGloFAS=False, river=None, binary=False):
"""Calculate MI
Intuitively, the MI between X and Y represents the reduction in the uncertainty of Y after
observing X (and vice versa). Notice that the MI is symmetric, i.e., I(X; Y ) = I(Y ; X).
Note: 06252023: form uniform 5-day time series, use -999 as missing data label
Params
------
stationID
varDict: dictionary of variables to consider, varDict has dataarrays
onGloFAS: True
Returns:
-------
mi, Estimated mutual information between each feature and the target.
"""
from sklearn.feature_selection import mutual_info_regression
import sklearn.preprocessing as skp
def genTS(arrIn, K, V):
#generate time series for 5-day uniform intervals
arrOut = np.zeros(daterng.shape) - 999
arrOut[K] = arrIn[V]
return arrOut
#06252023: TWS,P, and Q are created using valid TWS dates from raw CSR5d
# Q may have NaN values
TWS=varDict['TWS'].values
P =varDict['P'].values
#06252023: save the original CSR5d dates to timestamp for later use
timestamps = pd.to_datetime(varDict['P'].time.values)
if onGloFAS:
Q =varDict['Qs'].values
else:
Q =varDict['Q'].values
#========================
#08032023, add scatter plot on raw data
#========================
fitScatterPlot(cfg, stationID, varDict['TWS'], varDict['Q'], river=river)
#06252023: transform the variables
#In addition to missing CSR5D dates, we also need to account for missing Q
#Find index of NaN Q values and remove the same indices from all variables
#this assumes all numpy have the same temporal order
ind = np.where(~np.isnan(Q))[0]
orgArr = np.zeros(Q.shape, dtype=int)
orgArr[ind] = 1
TWS0 = TWS[ind]
P0 = P[ind]
Q0 = Q[ind]
#==============normalization================
doNormalization=True
if doNormalization:
#convert to gaussian
#Q = skp.PowerTransformer(method='box-cox').fit_transform(Q.reshape(-1,1)).squeeze()
Q0[Q0<=0] = 1e-4
Q0 = skp.PowerTransformer(method='box-cox').fit_transform(Q0.reshape(-1,1)).squeeze()
TWS0 = skp.PowerTransformer().fit_transform(TWS0.reshape(-1,1)).squeeze()
P0 = skp.PowerTransformer().fit_transform(P0.reshape(-1,1)).squeeze()
#get mutual information (MI) using Non-Null values
dfMI = pd.DataFrame({'TWS': TWS0, 'P': P0, 'Q': Q0})
mi_scores = mutual_info_regression(dfMI[['TWS', 'P']], dfMI['Q'], discrete_features='auto', n_neighbors=KNN)
mi_scores_twsonly = mutual_info_regression(dfMI[['TWS']], dfMI['Q'], discrete_features='auto', n_neighbors=KNN)
#06252023: replace the original values with transformed values
TWS[ind] = TWS0
P[ind] = P0
Q[ind] = Q0
#create a new daterng containing uniform 5-day dates
daterng = pd.date_range(start=timestamps[0], end=timestamps[-1], freq='5D')
#get key/value pairs to map from daterng to timestamps
K = []
V = []
for iy, t1 in enumerate(timestamps):
for ix, t2 in enumerate(daterng):
if abs((t1-t2).days)<3.0 and ~np.isnan(Q[iy]):
K.append(ix)
V.append(iy)
K = np.array(K)
V = np.array(V)
#assign values to 5-day dates, missing values are indicated by -999
TWS = genTS(TWS, K, V)
P = genTS(P, K, V)
Q = genTS(Q, K, V)
assert(len(TWS)==len(Q) and len(P)==len(Q) )
dfa = pd.DataFrame({'Q':Q, 'TWS':TWS, 'P': P}, index=daterng)
#=====get CMI ===========
cmi_score = getCMI(cfg, stationID, dfa, river=river, saveDataFrame=True)
#extract binary events
season = None
method_name = 'POT'
Q0 = Q[Q>-999]
TWS0 = TWS[TWS>-999]
P0 = P[P>-999]
cutoff = cfg.event.cutoff #this must be percent
#07/11, here timestamps[ind] are original CSR5d dates where Q is not NaN
eventQ = getExtremeEvents(pd.Series(Q0.squeeze(), index=timestamps[ind]), method=method_name,
cutoff=cutoff, transform=False, season=season)
eventTWS = getExtremeEvents(pd.Series(TWS0.squeeze(), index=timestamps[ind]), method=method_name,
cutoff=cutoff, transform=False,season=season)
eventP = getExtremeEvents(pd.Series(P0.squeeze(), index=timestamps[ind]), method=method_name,
cutoff=cutoff, transform=False,season=season)
#asun06242023, form arrays with missing data -999.
eQa = np.zeros(Q.shape)-999
eQa[Q>-999] = eventQ
ePa = np.zeros(P.shape)-999
ePa[P>-999] = eventP
eTWSa = np.zeros(TWS.shape)-999
eTWSa[TWS>-999] = eventTWS
#=====get Causal Links ===========
#do binary
dfBinary = pd.DataFrame({'Q': eQa, 'TWS': eTWSa, 'P': ePa})
causal_str_bin, sorted_links_bin, p_mat_bin ,val_mat_bin,ace_bin,ce_boot_bin = doCausalAnalytics(cfg, dfBinary, binary=True)
#do everything real-valued
causal_str, sorted_links, p_mat ,val_mat,ace, ce_boot = doCausalAnalytics(cfg, dfa)
return {'mi':mi_scores, 'cmi':cmi_score, 'mi_tws': mi_scores_twsonly,
'causal': causal_str,
'sorted_link': sorted_links,
'p_mat': p_mat,
'val_mat': val_mat,
'causal_bin': causal_str_bin,
'sorted_link_bin': sorted_links_bin,
'p_mat_bin': p_mat_bin,
'val_mat_bin': val_mat_bin,
'ace_bin': ace_bin,
'ace': ace,
'ce_boot_bin': ce_boot_bin,
'ce_boot': ce_boot
}
def getRegionBound(region, source='GRDC'):
"""
#asun 07012023: make the submaps equal sizes
#region, W, H
#NA 80 33
#EU 40 33
#AU 40 30
AF 40 30
SA 40 30
"""
if source=='GRDC':
#west, south, east, north
if region=='north_america':
#return (-130, 25, -50, 55)
return (-130, 25, -50, 58)
elif region == 'south_america':
#return (-90, -55, -5, 0)
return (-75, -25, -35, 5)
elif region == 'africa':
#return (-20, -35, 55, 40 )
#return (-20, -35, 55, 20)
return (10, -35, 50, -5)
elif region == 'europe':
#return (0, 40, 40, 80)
return (0, 30, 40, 63)
elif region == 'south_pacific':
#return (110, -45, 160, -10)
#return (130, -40, 155, -15)
return (115, -40, 155, -10)
elif region == 'asia':
return (60, 8, 145, 60)
else:
#west, south, east, north
if region=='north_america':
#return (-130, 25, -50, 55)
return (-130, 25, -50, 58)
elif region == 'south_america':
#return (-90, -55, -5, 0)
return (-90, -55, -5, 10)
elif region == 'africa':
#return (-20, -35, 55, 40 )
#return (-20, -35, 55, 20)
return (-10, -35, 50, 20)
elif region == 'europe':
#return (0, 40, 40, 80)
return (-10, 35, 60, 70)
elif region == 'south_pacific':
#return (110, -45, 160, -10)
#return (130, -40, 155, -15)
return (115, -40, 155, -10)
elif region == 'asia':
return (60, 8, 145, 60)
def discrete_cmap(N, base_cmap=None):
"""Create an N-bin discrete colormap from the specified input map"""
# Note that if base_cmap is a string or None, you can simply do
# return plt.cm.get_cmap(base_cmap, N)
# The following works for string, None, or a colormap instance:
base = plt.cm.get_cmap(base_cmap)
color_list = base(np.linspace(0, 1, N))
cmap_name = base.name + str(N)
return base.from_list(cmap_name, color_list, N)
def plotGlobalMap(allScores, region, gdfCatalog, dfStation, feature_column='TWS_MI', onGloFAS=False):
"""
Params
------
allScores, dictionary of metrics
region, region to be plotted
gdfCatalog, catalog of stations with metadata
dfStation, dataframe of station
onGloFAS, plot related to glofas
"""
#https://www.sc.eso.org/~bdias/pycoffee/codes/20160602/colorbar_demo.html
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.axes as maxes
import matplotlib as mpl
from shapely.geometry import Polygon
gdfAll = []
dfStation = gpd.GeoDataFrame(dfStation, geometry=gpd.points_from_xy(dfStation.long, dfStation.lat))
for key,val in allScores.items():
if key in dfStation['grdc_no'].to_list():
gdf = getBasinMask(stationID=key, region=region, gdf=gdfCatalog)
if 'mi' in val.keys():
gdf['TWS_MI'] = val['mi'][0]
gdf['P_MI'] = val['mi'][1]
gdf['T_MI'] = val['mi'][2]
gdf['TWS_CMI'] = val['cmi']
gdf['cmi_diff'] = val['cmi'] - val['mi'][0]
if 'NSE' in val.keys():
gdf['NSE'] = val['NSE']
if 'grdc_tws_tau' in val.keys():
gdf['grdc_tws_tau'] = val['grdc_tws_tau']
if 'grdc_glofas_tau' in val.keys():
gdf['grdc_glofas_tau'] = val['grdc_glofas_tau']
if 'grdc_precip_tau' in val.keys():
gdf['grdc_precip_tau'] = val['grdc_precip_tau']
if 'glofas_tws_tau' in val.keys():
gdf['glofas_tws_tau'] = val['glofas_tws_tau']
if 'grdc_tws_tau_ex' in val.keys():
gdf['grdc_tws_tau_ex'] = val['grdc_tws_tau_ex']
if 'grdc_glofas_tau_ex' in val.keys():
gdf['grdc_glofas_tau_ex'] = val['grdc_glofas_tau_ex']
if 'grdc_precip_tau_ex' in val.keys():
gdf['grdc_precip_tau_ex'] = val['grdc_precip_tau_ex']
if 'glofas_tws_tau_ex' in val.keys():
gdf['glofas_tws_tau_ex'] = val['glofas_tws_tau_ex']
gdfAll.append(gdf)
gdfAll = pd.concat(gdfAll)
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
if region !='global':
#lon0, lat0, lon1, lat1 = gdfAll.total_bounds
lon0, lat0, lon1, lat1 = getRegionBound(region)
#world = world.clip(Polygon([(lon0, lat0), (lon1,lat0), (lon1, lat1), (lon0, lat1), (lon0, lat0)]))
else:
lon0 = None
crs_new = ccrs.PlateCarree()
world = world.to_crs(crs_new)
gdfAll = gdfAll.to_crs(crs_new)
dfStation = dfStation.to_crs(crs_new)
#10/17, note gdfAll is sorted by decreasing areas
gdfAll = gdfAll.sort_values(by='area_hys') #, ascending=False)
#
# as 12/10/2022, filter by area_hys
#
gdfAll = gdfAll[gdfAll['area_hys']>MIN_BASIN_AREA]
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(1, 1, 1, projection=crs_new)
divider = make_axes_locatable(ax)
if feature_column == 'NSE':
#cmap = 'YlGnBu'
cmap = discrete_cmap(10, base_cmap='YlGnBu')
elif feature_column in ['grdc_tws_tau', 'grdc_glofas_tau', 'grdc_precip_tau', 'glofas_tws_tau',
'grdc_tws_tau_ex', 'grdc_glofas_tau_ex', 'grdc_precip_tau_ex', 'glofas_tws_tau_ex']:
cmap = 'YlGnBu'
else:
#cmap = cc.cm.fire_r
cmap = discrete_cmap(5, base_cmap='YlGnBu')
cax = divider.append_axes("right", size="5%", axes_class=maxes.Axes, pad=0.05)
gdfAll.plot(column=feature_column, ax=ax, alpha=0.7, legend=True, cax=cax,
vmin=0, vmax=1.0, cmap=cmap,
legend_kwds={'label': feature_column})
world.plot(ax=ax, alpha=0.5, facecolor="none", edgecolor='black')
if not lon0 is None:
ax.set_extent((lon0, lon1, lat0, lat1), crs_new)
# Plot lat/lon grid
gl = ax.gridlines(crs=crs_new, draw_labels=True,
linewidth=0.1, color='k', alpha=1,
linestyle='--')
#world_clipped.boundary.plot(ax=ax, color='gray', alpha=0.5)
#dfStation.plot(ax=ax, facecolor="none", edgecolor="black")
#ax.coastlines(resolution='110m', color='gray')
#ax.set_aspect('equal')
if onGloFAS:
ax.set_title(f'GloFAS {regionNames[region]}')
else:
ax.set_title(f'GRDC {regionNames[region]}')
if onGloFAS:
plt.savefig(f'grdcresults/glofas_{region}_{feature_column}.png')
else:
plt.savefig(f'grdcresults/{region}_{feature_column}.png')
plt.close()
def getStationMeta(dfRegion):
grdcfile = '/home/suna/work/grace/data/grdc/GRDC_Stations.csv'
df = pd.read_csv(grdcfile )
#join with dfRegion to get missing columns
dfJoin = pd.merge(
df,
dfRegion,
how="inner",
on='grdc_no',
sort=True,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
)
dfJoin = dfJoin.sort_values(by='area_hys', ascending=False)
return dfJoin
def getGloFASStations(dfRegion):
grdcfile = '/home/suna/work/grace/data/grdc/GRDC_Stations.csv'
df = pd.read_csv(grdcfile)
#join with dfRegion to get missing columns
dfJoin = pd.merge(
df,
dfRegion,
how="inner",