-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrdc.py
More file actions
executable file
·3459 lines (3027 loc) · 150 KB
/
Copy pathgrdc.py
File metadata and controls
executable file
·3459 lines (3027 loc) · 150 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
#GRDC Q unit m3/s
#CSR5d unit: cm
#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: 08022023, cleanup again
#rev date: decide on final runs:
# -- MAF on 5-day min dist for bivariate and compound event
# -- MAF on 5-day min dist for fake5d bivariate and compound event
#rev date: 08052023, implemented SWE removal set cfg.data.removeSWE to True in config.yaml
#rev date: 08072023, fixed bug in doSWERemoval, should use anomaly by subtracting mean SWE
#rev date: 09062023, revise to add two stations on yangtze river
#Requirements [can be installed via pip]
# rioxarray, cartopy, hydrostats, shapely, statsmodels, seaborn, tigramite
#=======================================================================================================
import pandas as pd
import os,sys
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 cartopy.crs as ccrs
import hydrostats as HydroStats
import colorcet as cc
from datetime import datetime
from scipy.stats import kendalltau, gumbel_r
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
import rioxarray as rxr
import seaborn as sns
import statsmodels.api as SM
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,getExtremeEvents,bandpass_filter,removeClimatology,getCompoundEvents,genColorList,genSingleColorList
from dataloader_global import load5ddatasets,loadClimatedatasets,getCSR5dLikeArray,loadTWSDataArray_SWE
import glofas_us
from glofas_us import extractBasinOutletQ, loadGLOFAS4CONUS
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",
"asia": "Asia",
"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 for CMI
KNN = 6
#BASIN AREA in [km^2]
MIN_BASIN_AREA = 1.2e5
def getBasinMask(stationID, region='north_america', gdf=None):
""" Get basin mask as a geopandas DF
09062023: note
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, basin mask is taken from the geojson file in each continent folder
when downloading station catalog, check the "download watershed polygon" box
"""
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/2022, 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
08052023: add removeSWE option
"""
gdf = getBasinMask(stationID=stationID, region=region, gdf=gdf)
region = getRegionExtent(regionName="global")
#TWS
#07142023: use TWS 0.25 for TWS masking, but ERA5 1deg for climate 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 load5ddatasets and loadClimatedatasets
# Step 2: turn coarsen to False, reload to True in load5ddatasets, but False in loadClimatedatasets
# During regular run, the first should print (1022, 720, 1440) (720, 1440)
if xds is None:
if not removeSWE:
print ('!!! Load original TWS')
xds,_, _ = load5ddatasets(region=region,
coarsen=False,
mask_ocean=config.data.mask_ocean,
removeSeason=config.data.remove_season,
reLoad=config.data.reload,
csr5d_version=config.data.csr5d_version,
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 with SWE removed')
#note: run loadTWSDataArray_SWE in dataloader_global to pre-save the data
xds = loadTWSDataArray_SWE(
region=region,
coarsen=False,
mask_ocean=config.data.mask_ocean,
removeSeason=config.data.remove_season,
reLoad=config.data.reload,
csr5d_version=config.data.csr5d_version,
startYear=datetime.strptime(config.data.start_date, '%Y/%m/%d').date().year,
endYear=datetime.strptime(config.data.end_date, '%Y/%m/%d').date().year,
)
if returnFPI:
#aggregate TWS to 1deg to be used w/ 1 deg precip data
xdsC = xds.coarsen(lat=4, lon=4).mean()
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)
basinP = getPredictor4Basin(gdf, lat, lon, xds_Precip)
#always use detrended twsDA to calculate fpi
if returnFPI:
basinFPI = getFPIData(gdf, xdsC, xds_Precip, gdf.crs, op='mean', weighting=True)
return basinTWS, basinP, basinFPI, xds, xds_Precip, xdsC
else:
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']
df['Q'] = pd.to_numeric(df['Q'])
#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.
Note: this return sorted links for Q only
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
#form tigramite dataframe
dataframe = pp.DataFrame(data,
datatime = {0:np.arange(data.shape[0])},
var_names=var_names,
missing_flag=-999.)
#Calculate CMI
pcmci = PCMCI(
dataframe=dataframe,
cond_ind_test=RobustParCorr(),
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:
#plot the max lagged correlation for each station
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()
#plot the scatter plots for each station
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()
#plot tigramite time series for each station [not used]
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= cfg.data.knn, #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)
# ==== Uncomment the following to do causal graph plot=======
# 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 variable!!!
# 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 the set of potential links
selected_links = {}
# N is the number of variables (nodes)
# link_assumptions[j] = {(i, -tau):"-?>" for i in range(self.N) for tau in range(1, tau_max+1)}
#This initializes the graph with entries graph[i,j,tau] = link_type, i.e., link from i to j
#@see documentation at
#https://github.com/jakobrunge/tigramite/blob/master/tigramite/pcmci.py
for i in range(len(var_names)):
selected_links[i] = {}
ivar=0
#TWS->Q, directed lagged links
for jvar in [0,1]:
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)]='-?>'
#P->Q, directed lagged links
ivar=0
jvar=2
for ilag in range(tau_min, tau_max+1):
selected_links[ivar][(jvar, -ilag)]='-?>'
#P->TWS directed lagged links
ivar = 1 #TWS
jvar = 2 #P
for ilag in range(tau_min, tau_max+1):
selected_links[ivar][(jvar, -ilag)]='-?>'
#add self links for P and TWS
for ivar in [1,2]:
for ilag in range(tau_min, tau_max+1):
selected_links[ivar][(ivar, -ilag)]='-?>'
pc_alpha = 0.1
alpha_level = 0.05
if binary:
#figuring out the causal relationship between extreme events
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=alpha_level)
#08222023, the following lines are the same between binary and continuous, can be combined!!!!
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)
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 )
#08212023, add printout of causal effect of TWSA and P at individual lags
target_var = 0 #Q
input_vars = [1,2] #TWSA, P
ce_dict={'TWSA':[], 'P':[]}
for invar in input_vars:
if invar == 1:
ce_dict['TWSA'] = [med.get_ce(i=invar, tau=-tau, j=target_var) for tau in range(tau_min, tau_max+1)]
elif invar == 2:
ce_dict['P'] = [med.get_ce(i=invar, tau=-tau, j=target_var) for tau in range(tau_min, tau_max+1)]
else:
pcmci = PCMCI(
dataframe=dataframe,
cond_ind_test= RobustParCorr()
)
results = pcmci.run_pcmci(
link_assumptions= selected_links,
tau_min=tau_min,
tau_max=tau_max,
pc_alpha=pc_alpha)
#Extract sorted causal links for Q only
outstr, sorted_links = print_significant_links(data.shape[1], var_names,
p_matrix=results['p_matrix'],
val_matrix=results['val_matrix'],
alpha_level=alpha_level)
print ("*****For Q only*****", sorted_links)
#08222023, the following lines are the same between binary and continuous, can be combined!!!!
med = LinearMediation(dataframe=dataframe)
#here use the all_parents from the PCMCI causal discovery
med.fit_model(all_parents=pcmci.all_parents, tau_max=tau_max)
med.fit_model_bootstrap(boot_blocklength=1, seed=28, boot_samples=200)
#at the lag of the maximum absolute causal effect
ace = med.get_all_ace(lag_mode='absmax', exclude_i=True)
ce_boots = med.get_bootstrap_of(function='get_all_ace', function_args={}, conf_lev=0.9)
#08212023, add printout of causal effect of TWSA and P at individual lags
target_var = 0 #Q
input_vars = [1,2] #TWSA, P
ce_dict={'TWSA':[], 'P':[]}
for invar in input_vars:
if invar == 1:
ce_dict['TWSA'] = [med.get_ce(i=invar, tau=-tau, j=target_var) for tau in range(tau_min, tau_max+1)]
elif invar == 2:
ce_dict['P'] = [med.get_ce(i=invar, tau=-tau, j=target_var) for tau in range(tau_min, tau_max+1)]
#
print ("average causal effect of TWS,P ", ace)
return outstr, sorted_links, results['p_matrix'],results['val_matrix'],ace,ce_boots,ce_dict
def fitScatterPlot(cfg, stationID, daTWS,daQ, daP, river):
#
tws = daTWS.values
Q = daQ.values
#08062023, linear model
if cfg.data.log_transform:
Q[Q<=0] = 1e-3
Q = np.log(Q)
#test if log linear relationship holds, lnQ = a+b*TWS
dfTemp = pd.DataFrame(np.c_[tws,Q],columns=('TWS', 'Q'))
dfTemp = dfTemp.dropna()
X = dfTemp['TWS'].values
Y = dfTemp['Q'].values
X = SM.add_constant(X)
#=--test model----
# X = np.arange(100)
# epsil = np.random.normal(0,0.01)
# Y = 10*X + 2.5 + epsil
# X = SM.add_constant(X)
mod = SM.OLS(Y,X)
res = mod.fit(use_t=True)
intercept, slope = res.params
pval = res.f_pvalue
print ("linear regression", intercept, slope, pval)
if cfg.event.season=="":
seasoncode = None
else:
seasoncode = cfg.event.season
resDict = getCompoundEvents(cfg, daQ, daP, daTWS, returnTS=True)
q_events = resDict['q_events']
tws_events = resDict['tws_events']
p_events = resDict['p_events']
timestamp = resDict['timestamp']
tws = resDict['TWS']
Q = resDict['Q']
#this does not work for seasonal
if seasoncode is None:
assert (len(tws_events) == len(timestamp))
#define quandrants of scatter plot
#note if there's missing record, the extreme will not show up on the plots
groups={'I':[], 'II':[], 'III':[], "IV":[]}
#asun 09142023, fixed bug
#need to consider event tolerance when plotting
#first we need to do nudging for two events in the same window
tws_annual_events = np.where(tws_events==1)[0]
q_annual_events = np.where(q_events==1)[0]
timestamp = pd.to_datetime(timestamp)
#we set events in the same window to the tws date
for iy in q_annual_events:
for ix in tws_annual_events:
dt = (timestamp[iy]-timestamp[ix]).days
if abs(dt)<=cfg.event.t_win:
#switch to Q dates
q_events[iy] = 0
q_events[ix] = 1
#now we do plotting
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]])
_, ax = plt.subplots(1,1,figsize=(6,6))
for key in groups.keys():
groups[key] = np.array(groups[key])
if key == 'I':
symbolcolor='#BDC3C7'
marker = 'o'
alpha = 0.7
markersize = 4
label = 'I'
elif key == 'II':
symbolcolor='#007FD3'
marker = 'o'
alpha = 1
markersize = 7
label = 'II (Q)'
elif key == 'III':
symbolcolor='#2ECC71'
marker = 'o'
alpha = 1
markersize = 7
label = 'III (TWSA)'
else:
symbolcolor='#af0f2b'
marker = '*'
alpha = 1
markersize = 11
label = 'IV (Q^TWSA)'
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)
if cfg.data.log_transform and pval<0.05:
fit_Q = intercept+slope*tws
ax.plot(tws, fit_Q, color='k', linewidth=1.0)
ax.text(0.02, 0.02, f'pval={pval:4.2f}', fontsize=12, transform=ax.transAxes)
ax.set_ylabel('log-Q, [m/(km^2 s]',fontsize=14)
else:
ax.set_ylabel('Q, [m/(km^2 s]', fontsize=14)
ax.set_xlabel('TWSA [cm]', fontsize=14)
ax.set_title(f'Station {stationID}, {river}',fontsize=15)
plt.legend(loc='best', fontsize=15)
if cfg.data.log_transform:
logs = "log"
else:
logs = ""
if not cfg.data.deseason:
if cfg.event.event_method == 'MAF':
plt.savefig(f'outputs/scatter_raw_{stationID}_{cfg.event.t_win}{cfg.event.season}{logs}.eps')
plt.savefig(f'outputs/scatter_raw_{stationID}_{cfg.event.t_win}{cfg.event.season}{logs}.png')
else:
plt.savefig(f'outputs/scatter_raw_{stationID}_{cfg.event.t_win}{cfg.event.season}_{cfg.event.event_method}{cfg.event.cutoff}{logs}.png')
else:
if cfg.event.event_method == "MAF":
plt.savefig(f'outputs/noseason_scatter_raw_{stationID}_{cfg.event.t_win}{cfg.event.season}{logs}.png')
else:
plt.savefig(f'outputs/noseason_scatter_raw_{stationID}_{cfg.event.t_win}{cfg.event.season}_{cfg.event.event_method}{cfg.event.cutoff}{logs}.png')
plt.close()
if cfg.data.log_transform:
return pval
def calculateMetrics(cfg, stationID, varDict, onGloFAS=False, river=None, binary=False):
"""Main route for calculating all metrics
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)
pval = -1
if onGloFAS:
Q =varDict['Qs'].values
else:
Q =varDict['Q'].values
#========================
#08022023, add scatter plot on raw data
#========================
pval = fitScatterPlot(cfg, stationID, varDict['TWS'], varDict['Q'], varDict['P'], 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 distributions
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
#for POT, no minDIST is required
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,ce_dict = doCausalAnalytics(cfg, dfBinary, binary=True)
#do everything real-valued
causal_str, sorted_links, p_mat ,val_mat,ace, ce_boot, ce_dict = 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,
'pval': pval,
'ce_dict': ce_dict
}
def getRegionBound(region, source='GRDC'):
"""These are used for plotting Figure 1
#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)
return (-140, 25, -50, 58)
elif region == 'south_america':
#return (-90, -55, -5, 0)
#return (-75, -25, -35, 5)
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)
return (0, 20, 40, 65)
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)
return (100, 20, 140, 50)
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):
"""Plot global map [NOT USED!!!]
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: