-
Notifications
You must be signed in to change notification settings - Fork 0
/
runcity_xgboost.py
executable file
·3401 lines (3338 loc) · 158 KB
/
runcity_xgboost.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 20:45:30 2021
@author: ghkerr
"""
DIR = '/Users/ghkerr/GW/'
DIR_MODEL = DIR+'data/GEOSCF/'
DIR_MOBILITY = DIR+'data/mobility/'
DIR_FIG = DIR+'mobility/figs/'
DIR_AQ = DIR+'data/aq/'
DIR_TYPEFACE = '/Users/ghkerr/Library/Fonts/'
DIR_EMISSIONS = DIR+'data/emissions/'
agorange = '#CD5733'
agtan = '#F4E7C5'
agnavy = '#678096'
agblue = '#ACC2CF'
agpuke = '#979461'
agred = '#A12A19'
# Load custom font
import numpy as np
import sys
sys.path.append('/Users/ghkerr/GW/mobility/')
import readc40aq
import readc40mobility
if 'mpl' not in sys.modules:
import matplotlib.font_manager
prop = matplotlib.font_manager.FontProperties(
fname=DIR_TYPEFACE+'cmunbmr.ttf')
matplotlib.rcParams['font.family'] = prop.get_name()
matplotlib.rcParams['mathtext.rm'] = prop.get_name()
prop = matplotlib.font_manager.FontProperties(
fname=DIR_TYPEFACE+'cmunbbx.ttf')
matplotlib.rcParams['mathtext.bf'] = prop.get_name()
prop = matplotlib.font_manager.FontProperties(
fname=DIR_TYPEFACE+'cmunbmo.otf')
matplotlib.rcParams['mathtext.it'] = prop.get_name()
matplotlib.rcParams['axes.unicode_minus'] = False
# Functions
def adjacent_values(vals, q1, q3):
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
return lower_adjacent_value, upper_adjacent_value
def draw_brace(ax, yspan, xx, color):
"""Draws an annotated brace on the axes."""
ymin, ymax = yspan
yspan = ymax - ymin
ax_ymin, ax_ymax = ax.get_ylim()
yax_span = ax_ymax - ax_ymin
xmin, xmax = ax.get_xlim()
xspan = xmax - xmin
resolution = int(yspan/yax_span*100)*2+1 # guaranteed uneven
beta = 300./yax_span # the higher this is, the smaller the radius
y = np.linspace(ymin, ymax, resolution)
y_half = y[:int(resolution/2)+1]
x_half_brace = (1/(1.+np.exp(-beta*(y_half-y_half[0])))
+ 1/(1.+np.exp(-beta*(y_half-y_half[-1]))))
x = np.concatenate((x_half_brace, x_half_brace[-2::-1]))
x = xx + (.05*x - .01)*xspan # adjust vertical position
ax.plot(-x, y, color=color, lw=1, clip_on=False)
return
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
import matplotlib.colors as colors
new_cmap = colors.LinearSegmentedColormap.from_list(
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval,
b=maxval), cmap(np.linspace(minval, maxval, n)))
return new_cmap
def fit_func(p, t):
"""First order linear regression for calculating total least squares
"""
return p[0] * t + p[1]
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
def geo_idx(dd, dd_array):
"""Function searches for nearest decimal degree in an array of decimal
degrees and returns the index. np.argmin returns the indices of minimum
value along an axis.
Parameters
----------
dd : int
Latitude or longitude whose index in dd_array is being sought
dd_array : numpy.ndarray
1D array of latitude or longitude
Returns
-------
geo_idx : int
Index of latitude or longitude in dd_array that is closest in value to
dd
"""
import numpy as np
from scipy import stats
geo_idx = (np.abs(dd_array - dd)).argmin()
# If distance from closest cell to intended value is "far", raise error
if np.abs(dd_array[geo_idx] - dd) > 1.:
return
return geo_idx
# From https://stackoverflow.com/questions/16107884/
# power-law-with-a-constant-factor-using-curve-fitting; note that the
# initial conditions for a and b came from the first y and x values
# (assuming values are in order), c can be estimated as in the accepted
# answer, and the estimate for d came from the final y values which are ~0.
# If you're having trouble with initial conditions, this can be a good
# starting point (see https://stackoverflow.com/questions/21420792/
# exponential-curve-fitting-in-scipy for more information)
def func(x, a, c, d):
return a*np.exp(-c*x)+d
def build_focuscities(noC40):
"""Build table of focus cities for this study.
Parameters
----------
noc40 : bool
If True, C40 cities outside of the European Union will be dropped from
the DataFrame.
Returns
-------
focuscities : pandas.core.frame.DataFrame
Table containing city names, countries, population, share of passenger
vehicles using diesel fuel, and lockdown start and end dates.
"""
import numpy as np
import pandas as pd
from itertools import groupby
def ranges(lst):
pos = (j - i for i, j in enumerate(lst))
t = 0
for i, els in groupby(pos):
l = len(list(els))
el = lst[t]
t += l
yield range(el, el+l)
# City | Country | Passenger diesel %
# focuscities = [['Amsterdam', 'Netherlands', 14.0], # ACEA
# ['Athens', 'Greece', 8.1], # ACEA
# ['Auckland C40', 'New Zealand', 8.3], # C40 partnership
# ['Barcelona', 'Spain', 58.7], # ACEA
# ['Berlin C40', 'Germany', 31.7], # ACEA
# ['Bucharest', 'Romania', 43.3], # ACEA
# ['Budapest', 'Hungary', 31.5], # ACEA
# ['Cologne', 'Germany', 31.7], # ACEA
# ['Copenhagen', 'Denmark', 30.9], # ACEA
# ['Dusseldorf', 'Germany', 31.7], # ACEA
# ['Frankfurt', 'Germany', 31.7], # ACEA
# ['Hamburg', 'Germany', 31.7], # ACEA
# ['Helsinki', 'Finland', 27.9], # ACEA
# ['Krakow', 'Poland', 31.6], # ACEA
# ['Lodz', 'Poland', 31.6], # ACEA
# ['London C40', 'United Kingdom', 39.0], # ACEA
# ['Los Angeles C40', 'United States', 0.4], # C40 partnership
# ['Madrid', 'Spain', 58.7], # ACEA
# ['Marseille', 'France', 58.9], # ACEA
# ['Mexico City C40', 'Mexico', 0.2], # C40 partnership
# ['Milan C40', 'Italy', 44.2], # ACEA
# ['Munich', 'Germany', 31.7], # ACEA
# ['Naples', 'Italy', 44.2], # ACEA
# ['Palermo', 'Italy', 44.2], # ACEA
# ['Paris', 'France', 58.9], # ACEA
# ['Prague', 'Czechia', 35.9], # ACEA
# ['Rome', 'Italy', 44.2], # ACEA
# ['Rotterdam', 'Netherlands', 14.0], # ACEA
# ['Santiago C40', 'Chile', 7.1], # C40 partnership
# ['Saragossa', 'Spain', 58.7], # ACEA
# ['Seville', 'Spain', 58.7], # ACEA
# ['Sofia', 'Bulgaria', 43.1], # ICCT partnership
# ['Stockholm', 'Sweden', 35.5], # ACEA
# ['Stuttgart', 'Germany', 31.7], # ACEA
# ['Turin', 'Italy', 44.2], # ACEA
# ['Valencia', 'Spain', 58.7], # ACEA
# ['Vienna', 'Austria', 55.0], # ACEA
# ['Vilnius', 'Lithuania', 69.2], # ACEA
# ['Warsaw', 'Poland', 31.6], # ACEA
# ['Wroclaw', 'Poland', 31.6], # ACEA
# ['Zagreb', 'Croatia', 52.4], # ACEA
# ]
focuscities = [
['Athens', 'Greece', 8.1, 16.0], # ACEA
['Auckland C40', 'New Zealand', 8.3, 999], # C40 partnership
['Barcelona', 'Spain', 58.7, 12.7], # ACEA
['Berlin', 'Germany', 31.7, 9.6], # ACEA
['Budapest', 'Hungary', 31.5, 13.5], # ACEA
['Copenhagen', 'Denmark', 30.9, 8.8], # ACEA
['Helsinki', 'Finland', 27.9, 12.2], # ACEA
['Krakow', 'Poland', 31.6, 41.1], # ACEA
['London C40', 'United Kingdom', 39.0, 8.0], # ACEA
['Los Angeles C40', 'United States', 0.4, 999], # C40 partnership
['Madrid', 'Spain', 58.7, 12.7], # ACEA
['Marseille', 'France', 58.9, 10.2], # ACEA
['Mexico City C40', 'Mexico', 0.2, 999], # C40 partnership
['Milan', 'Italy', 44.2, 11.4], # ACEA
['Munich', 'Germany', 31.7, 9.6], # ACEA
['Paris', 'France', 58.9, 10.2], # ACEA
['Prague', 'Czechia', 35.9, 14.9], # ACEA
['Rome', 'Italy', 44.2, 11.4], # ACEA
['Rotterdam', 'Netherlands', 14.0, 11.0], # ACEA
['Santiago C40', 'Chile', 7.1, 999], # C40 partnership
['Sofia', 'Bulgaria', 43.1, 22], # ICCT partnership
['Stockholm', 'Sweden', 35.5, 10.], # ACEA
['Vienna', 'Austria', 55.0, 8.3], # ACEA
['Vilnius', 'Lithuania', 69.2, 16.8], # ACEA
['Warsaw', 'Poland', 31.6, 41.1], # ACEA
['Zagreb', 'Croatia', 52.4, 14.6], # ACEA
]
focuscities = pd.DataFrame(focuscities, columns=['City', 'Country',
'Diesel share', 'Age'])
# Open stay-at-home data
sah = pd.read_csv(DIR_MOBILITY+'stay-at-home-covid.csv')
# Meaning of column stay_home_requirements
# 0 = No measures
# 1 = Recommended not to leave the house
# 2 = Required to not leave the house with exceptions for daily
# exercise, grocery shopping, and ‘essential’ trips
# 3 = Required to not leave the house with minimal exceptions (e.g.
# allowed to leave only once every few days, or only one person
# can leave at a time, etc.)
# Add stay at home requirements to city information DataFrame
focuscities['start'] = np.nan
focuscities['end'] = np.nan
focuscities['startreq'] = np.nan
focuscities['endreq'] = np.nan
# Loop through cities and determine the dates of lockdowns
for index, row in focuscities.iterrows():
country = row['Country']
sah_country = sah.loc[sah['Entity']==country]
# Restrict to measuring period
sah_country = sah_country.loc[sah_country['Day']<'2020-07-01']
# Occurrences of ALL recommended or required stay-at-home measures
where1 = np.where(sah_country['stay_home_requirements']==1.)[0]
where2 = np.where(sah_country['stay_home_requirements']==2.)[0]
where3 = np.where(sah_country['stay_home_requirements']==3.)[0]
start = min(np.hstack([where1,where2,where3]))
startdate = sah_country['Day'].values[start]
end = max(np.hstack([where1,where2,where3]))
enddate = sah_country['Day'].values[end]
if pd.to_datetime(enddate) > pd.to_datetime('2020-06-30'):
enddate = '2020-06-30'
focuscities.loc[index, 'start'] = startdate
focuscities.loc[index, 'end'] = enddate
# Occurrences of REQUIRED stay-at-home measures
if (np.shape(where2)[0]!=0) or (np.shape(where3)[0]!=0):
start = min(np.hstack([where2,where3]))
startdate = sah_country['Day'].values[start]
end = max(np.hstack([where2,where3]))
enddate = sah_country['Day'].values[end]
if pd.to_datetime(enddate) > pd.to_datetime('2020-06-30'):
enddate = '2020-06-30'
focuscities.loc[index, 'startreq'] = startdate
focuscities.loc[index, 'endreq'] = enddate
else:
focuscities.loc[index, 'startreq'] = np.nan
focuscities.loc[index, 'endreq'] = np.nan
if noC40==True:
focuscities.drop(focuscities.loc[focuscities['City'].isin([
'Auckland C40', 'Los Angeles C40', 'Mexico City C40',
'Santiago C40'])].index, inplace=True)
return focuscities
def fig2():
"""
"""
import numpy as np
import pandas as pd
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import matplotlib.pyplot as plt
import matplotlib.colors as colors
# Number of features to plot
nft = 10
# Reduce data to first NFEATURES number of features, and sort by median
medians = shaps_concat.median()
medians = pd.DataFrame(medians).sort_values(by=0,ascending=False)
features = list(medians.index[:nft])
medians_lon = shaps_lon.median()
medians_lon = pd.DataFrame(medians_lon).sort_values(by=0,ascending=False)
features_lon = list(medians_lon.index[:nft])
# Plotting
fig = plt.figure(figsize=(10,4))
ax1 = plt.subplot2grid((1,3),(0,0), colspan=2)
ax2 = plt.subplot2grid((1,3),(0,2), colspan=1)
# Pluck of observations and GEOS-CF for London
bcm_lon = bcm.loc[bcm['City']=='London C40'].set_index('Date')
raw_lon = raw.loc[raw['City']=='London C40'].set_index('Date')
# Print performance metrics for paper
idx = np.isfinite(raw_lon['NO2'][:'2019-12-31'].values) & \
np.isfinite(bcm_lon['observed'][:'2019-12-31'].values)
print('r for London (GEOS-CF, observed), 2019')
print(np.corrcoef(raw_lon['NO2'][:'2019-12-31'].values[idx],
bcm_lon['observed'][:'2019-12-31'].values[idx])[0,1])
print('MFB for London (GEOS-CF, observed), 2019')
print((2*(np.nansum(raw_lon['NO2'][:'2019-12-31'].values-
bcm_lon['observed'][:'2019-12-31'].values)/np.nansum(
raw_lon['NO2'][:'2019-12-31'].values+
bcm_lon['observed'][:'2019-12-31'].values))))
print('r for London (GEOS-CF, BAU), 2019')
print(np.corrcoef(bcm_lon['predicted'][:'2019-12-31'].values[idx],
bcm_lon['observed'][:'2019-12-31'].values[idx])[0,1])
print('MFB for London (GEOS-CF, BAU), 2019')
print((2*(np.nansum(bcm_lon['predicted'][:'2019-12-31'].values-
bcm_lon['observed'][:'2019-12-31'].values)/np.nansum(
bcm_lon['predicted'][:'2019-12-31'].values+
bcm_lon['observed'][:'2019-12-31'].values))))
bcm_lon = bcm_lon.resample('1D').mean().rolling(window=7,
min_periods=1).mean()
raw_lon = raw_lon.resample('1D').mean().rolling(
window=7,min_periods=1).mean()
ax1.plot(raw_lon['NO2'], ls='--', color='darkgrey', label='GEOS-CF')
ax1.plot(bcm_lon['predicted'], '--k', label='Business-as-usual')
ax1.plot(bcm_lon['observed'], '-k', label='Observed')
# Fill red for positive difference between , blue for negative difference
y1positive=(bcm_lon['observed']-bcm_lon['predicted'])>0
y1negative=(bcm_lon['observed']-bcm_lon['predicted'])<=0
# ax.fill_between(dat.index, dat['predicted'],
# dat['observed'], where=y1positive, color='red', alpha=0.5)
ax1.fill_between(bcm_lon.index, bcm_lon['predicted'],
bcm_lon['observed'], where=y1negative, color=agnavy,
interpolate=True)
# Draw shaded gradient region for lockdown
ld_lon = focuscities.loc[focuscities['City']=='London C40']
ldstart = pd.to_datetime(ld_lon['start'].values[0])
ldend = pd.to_datetime(ld_lon['end'].values[0])
x = pd.date_range(ldstart,ldend)
y = range(37)
z = [[z] * len(x) for z in range(len(y))]
num_bars = 100 # More bars = smoother gradient
cmap = plt.get_cmap('Reds')
new_cmap = truncate_colormap(cmap, 0.0, 0.35)
ax1.contourf(x, y, z, num_bars, cmap=new_cmap, zorder=0)
ax1.text(x[int(x.shape[0]/2.)-2], 4, 'LOCKDOWN', ha='center',
rotation=0, va='center', fontsize=12)
# Aesthetics
ax1.set_ylim([0,36])
ax1.set_yticks(np.linspace(0,36,7))
# Hide the right and top spines
for side in ['right', 'top']:
ax1.spines[side].set_visible(False)
ax1.set_ylabel('NO$_{2}$ [ppbv]')
ax1.set_xlim([pd.to_datetime('2019-01-01'),pd.to_datetime('2020-06-30')])
ax1.set_xticks(['2019-01-01', '2019-02-01', '2019-03-01', '2019-04-01',
'2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01',
'2019-09-01', '2019-10-01', '2019-11-01', '2019-12-01',
'2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01',
'2020-05-01', '2020-06-01'])
ax1.set_xticklabels(['Jan\n2019', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan\n2020', 'Feb',
'Mar', 'Apr', 'May', 'Jun'], fontsize=9)
# Legend
ax1.legend(frameon=False, ncol=3, loc=3, fontsize=10)
# Replace variables names with something more
# publication-worthy
vardict = {'O3':'O$_{\mathregular{3}}$',
'NO2':'NO$_{\mathregular{2}}$',
'Volume':'Traffic',
'ZPBL':'Boundary layer height',
'V':'Northward wind',
'U':'Eastward wind',
'RH':'Relative humidity',
'Q':'Specific humidity',
'T':'Temperature',
'CO':'CO',
'PM25':'PM$_{\mathregular{2.5}}$',
'PS':'Surface pressure'}
colorlon = '#E69F00'
colorall = '#56B4E9'
# Plot boxplot and labels
for i,var in enumerate(features):
bplot = ax2.boxplot(shaps_concat[var].values, positions=[i],
widths=[0.5], patch_artist=True, whis=(10,90), vert=False,
showfliers=False)
ax2.text(np.percentile(shaps_concat[var].values, 90)+0.03, i,
vardict[var], ha='left', va='center', fontsize=9)
for item in ['boxes', 'whiskers', 'fliers']:
plt.setp(bplot[item], color=agorange)
for item in ['medians', 'caps']:
plt.setp(bplot[item], color='w')
vardict = {'O3':'O$_{\mathregular{3}}$',
'NO2':'NO$_{\mathregular{2}}$',
'Volume':'Traffic',
'ZPBL':'Boundary layer height',
'V':'Northward\nwind',
'U':'Eastward wind',
'RH':'Relative humidity',
'Q':'Specific humidity',
'T':'Temperature',
'CO':'CO',
'PM25':'PM$_{\mathregular{2.5}}$',
'PS':'Surface pressure'}
for i, var in enumerate(features_lon):
bplot_lon = ax2.boxplot(shaps_lon[var], positions=[i+12],
widths=[0.5], patch_artist=True, whis=(10,90), vert=False,
showfliers=False)
ax2.text(np.percentile(shaps_lon[var].values, 90)+0.03, i+12,
vardict[var], ha='left', va='center', fontsize=9, clip_on=False)
for item in ['boxes', 'whiskers', 'fliers']:
plt.setp(bplot_lon[item], color=agnavy)
for item in ['medians', 'caps']:
plt.setp(bplot_lon[item], color='w')
draw_brace(ax2, (0, 9), 0., agorange)
draw_brace(ax2, (12, 21), 0., agnavy)
ax2.text(-0.3, 16.5, 'London', rotation=90, ha='center', va='center',
color=agnavy)
ax2.text(-0.3, 4.5, 'All', rotation=90, ha='center', va='center',
color=agorange)
ax2.set_xlim([0,2.5])
ax2.set_xticks([0,0.5,1.,1.5,2.,2.5])
# ax2.set_xticklabels(['0.0','','0.5','','1.0','','1.5'], fontsize=9)
ax2.set_ylim([-0.5,22.])
ax2.set_yticks([])
ax2.invert_yaxis()
for side in ['left', 'right', 'top']:
ax2.spines[side].set_visible(False)
plt.subplots_adjust(left=0.05, right=0.92)
ax1.set_title('(a) London', x=0.1, y=1.02, fontsize=12)
ax2.set_title('(b) Absolute SHAP values', y=1.02, loc='left', fontsize=12)
plt.savefig(DIR_FIG+'fig2.pdf', dpi=1000)
return
def fig3(focuscities, bcm):
"""
Parameters
----------
focuscities : pandas.core.frame.DataFrame
Table containing city names, countries, population, share of passenger
vehicles using diesel fuel, and lockdown start and end dates.
bcm : pandas.core.frame.DataFrame
XGBoost-predicted concentrations and the observed concentrations
(and the bias) for focus cities
Returns
-------
None
"""
from sklearn.metrics import mean_squared_error
import math
from scipy.optimize import curve_fit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from dateutil.relativedelta import relativedelta
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import scipy.odr
from scipy import stats
dno2, no2, diesel, cities = [], [], [], []
for index, row in focuscities.iterrows():
city = row['City']
print(city)
bcm_city = bcm.loc[bcm['City']==city]
bcm_city.set_index('Date', inplace=True)
# Figure out lockdown dates
ldstart = focuscities.loc[focuscities['City']==city]['start'].values[0]
ldstart = pd.to_datetime(ldstart)
ldend = focuscities.loc[focuscities['City']==city]['end'].values[0]
ldend = pd.to_datetime(ldend)
# Calculate percentage change in NO2 during lockdown periods
before = np.nanmean(bcm_city.loc[ldstart-relativedelta(years=1):
ldend-relativedelta(years=1)]['predicted'])
after = np.abs(np.nanmean(bcm_city.loc[ldstart:ldend]['anomaly']))
pchange = -after/before*100
# Save output
dno2.append(pchange)
no2.append(bcm_city['observed']['2019-01-01':'2019-12-31'].mean())
diesel.append(focuscities.loc[focuscities['City']==city]['Diesel share'].values[0])
cities.append(focuscities.loc[focuscities['City']==city]['City'].values[0])
diesel = np.array(diesel)
cities = np.array(cities)
no2 = np.array(no2)
dno2 = np.array(dno2)
# Create custom colormap
cmap = plt.get_cmap("pink_r")
cmap = truncate_colormap(cmap, 0.4, 0.9)
cmaplist = [cmap(i) for i in range(cmap.N)]
cmap = mpl.colors.LinearSegmentedColormap.from_list('Custom cmap',
cmaplist, cmap.N)
cmap.set_over(color='k')
bounds = np.linspace(8, 20, 7)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
# Plotting
fig = plt.figure(figsize=(6,4))
ax1 = plt.subplot2grid((1,1),(0,0))
mb = ax1.scatter(diesel, dno2, c=no2, s=18, cmap=cmap, norm=norm,
clip_on=False)
ax1.set_xlabel(r'Diesel-powered passenger vehicle share [%]')
ax1.set_ylabel(r'$\mathregular{\Delta}$ NO$_{\mathregular{2}}$ [%]')
# Calculate slope with total least squares (ODR)
lincoeff = np.poly1d(np.polyfit(diesel, dno2, 1))
ax1.plot(np.unique(diesel), np.poly1d(np.polyfit(diesel, dno2, 1)
)(np.unique(diesel)), 'black', ls='dashed', lw=1, zorder=0,
label='Linear fit (y=ax+b)\na=-0.53, b=-2.21')
ax1.legend(frameon=False, bbox_to_anchor=(0.4, 0.5))
ax1.text(8.2, -45.3, 'r=-0.50\np=0.02')
axins1 = inset_axes(ax1, width='40%', height='5%', loc='lower left',
bbox_to_anchor=(0.02, 0.04, 1, 1), bbox_transform=ax1.transAxes,
borderpad=0)
fig.colorbar(mb, cax=axins1, orientation="horizontal", extend='both',
label='NO$_{\mathregular{2}}$ [ppbv]')
axins1.xaxis.set_ticks_position('top')
axins1.xaxis.set_label_position('top')
ax1.tick_params(labelsize=9)
ax1.set_xlim([-1,71])
ax1.set_ylim([-65,5])
# Calculate r, RMSE for linear vs. power fit
dno2_sorted = sort_list(dno2, diesel)
slope, intercept, r_value, p_value, std_err = stats.linregress(
dno2, diesel)
print('Equation coefficients should match the following:')
print('Linear: ', lincoeff)
print('Linear correlation between diesel and dNO2=', r_value)
print('p-value=',p_value)
print('RMSE for linear fit...', math.sqrt(mean_squared_error(dno2_sorted,
np.poly1d(np.polyfit(diesel, dno2, 1)
)(diesel))))
# for i, txt in enumerate(cities):
# if txt == 'Santiago C40':
# txt = 'Santiago'
# elif txt == 'Mexico City C40':
# txt = 'Mexico City'
# elif txt == 'Los Angeles C40':
# txt = 'Los Angeles'
# elif txt == 'Berlin C40':
# txt = 'Berlin'
# elif txt == 'Milan C40':
# txt = 'Milan'
# elif txt == 'London C40':
# txt = 'London'
# elif txt == 'Auckland C40':
# txt = 'Auckland'
# ax1.annotate(txt, (diesel[i]+1, dno2[i]+1), fontsize=9)
# plt.savefig(DIR_FIG+'fig3_citynames.png', dpi=1000)
plt.savefig(DIR_FIG+'fig3.pdf', dpi=1000)
return
def fig4():
"""
Returns
-------
None.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from dateutil.relativedelta import relativedelta
from scipy import stats
dno2, no2, diesel, cities = [], [], [], []
for index, row in focuscities.iterrows():
city = row['City']
print(city)
bcm_city = bcm.loc[bcm['City']==city]
bcm_city.set_index('Date', inplace=True)
# Figure out lockdown dates
ldstart = focuscities.loc[focuscities['City']==city]['start'].values[0]
ldstart = pd.to_datetime(ldstart)
ldend = focuscities.loc[focuscities['City']==city]['end'].values[0]
ldend = pd.to_datetime(ldend)
# Calculate percentage change in NO2 during lockdown periods
before = np.nanmean(bcm_city.loc[ldstart-relativedelta(years=1):
ldend-relativedelta(years=1)]['predicted'])
after = np.abs(np.nanmean(bcm_city.loc[ldstart:ldend]['anomaly']))
pchange = -after/before*100
# Save output
dno2.append(pchange)
no2.append(bcm_city['observed']['2019-01-01':'2019-12-31'].mean())
diesel.append(focuscities.loc[focuscities['City']==city]['Diesel share'].values[0])
cities.append(focuscities.loc[focuscities['City']==city]['City'].values[0])
diesel = np.array(diesel)
cities = np.array(cities)
no2 = np.array(no2)
dno2 = np.array(dno2)
# Open GAINS ECLIPSE
eclipse, coa2 = [], []
for city in cities:
# Find corresponding country to city
ccountry = focuscities.loc[focuscities['City']==city]['Country'].values[0]
if ccountry == 'United Kingdom':
ccountry = 'United-Kingdom'
eclipse_country = pd.read_csv(DIR_EMISSIONS+'gains/ECLIPSE_%s.csv'
%ccountry, sep=',', skiprows=7, engine='python')
coa2_country = pd.read_csv(DIR_EMISSIONS+'gains/COA2_%s.csv'%ccountry,
sep=',', skiprows=7, engine='python')
# Sample ratio of NOx from light-duty vehicles to total NOx emissions
# for 2020
eclipse_light = eclipse_country.loc[eclipse_country['[kt/yr]']==
'Light duty vehicles']['2020']
eclipse_total = eclipse_country.loc[eclipse_country['[kt/yr]']=='Sum']['2020']
eclipse.append(float(eclipse_light.values[0])/
float(eclipse_total.values[0]))
coa2_light = coa2_country.loc[coa2_country['[kt/yr]']==
'Light duty vehicles']['2020']
coa2_total = coa2_country.loc[coa2_country['[kt/yr]']=='Sum']['2020']
coa2.append(float(coa2_light.values[0])/float(coa2_total.values[0]))
eclipse = np.array(eclipse)
coa2 = np.array(coa2)
ensemble = np.nanmean(np.stack([eclipse, coa2]), axis=0)*100.
# Plotting
fig = plt.figure(figsize=(9.5,4))
ax1 = plt.subplot2grid((1,3),(0,0))
ax2 = plt.subplot2grid((1,3),(0,1), colspan=2)
# Hypothesis plot
# Define numbers of generated data points and bins per axis.
np.random.seed(7)
x = np.linspace(0, 100, 22) # 1000 values between 0 and 100
delta = np.random.uniform(0, 15, x.size)
y = -0.4*x + delta + 36
x[x<1]=np.nan
y[y<5.] = np.nan
ymask = np.isfinite(y) & np.isfinite(x)
ax1.hist2d(x[ymask], y[ymask], bins=4, cmap='Greys', alpha=0.3)
ax1.scatter(x, y, color='k', clip_on=False)
ax1.text(0.95, 0.03, 'Larger $\mathregular{\Delta}$NO$_{\mathregular{2}}$,'+
' Larger light-duty\nvehicle contribution ',
transform=ax1.transAxes, fontsize=7, ha='right')
ax1.text(0.05, 0.98, 'Smaller $\mathregular{\Delta}$NO$_{\mathregular{2}}$,'+
' Smaller light-duty\nvehicle contribution', clip_on=False,
transform=ax1.transAxes, fontsize=7, va='top', ha='left')
ax1.spines['left'].set_position('zero')
ax1.spines['right'].set_visible(False)
ax1.spines['bottom'].set_position('zero')
ax1.spines['top'].set_visible(False)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_ylim([0,52])
ax1.set_xticks([])
ax1.set_yticks([])
# Make arrows
ax1.plot((1), (0), ls="", marker=">", ms=7, color="k",
transform=ax1.get_yaxis_transform(), clip_on=False)
ax1.plot((0), (0.02), ls="", marker="v", ms=7, color="k",
transform=ax1.get_xaxis_transform(), clip_on=False)
ax1.set_xlabel('Increasing importance of\nlight-duty vehicle NO$_{x}$',
loc='center')
ax1.set_ylabel('Increasing NO$_{\mathregular{2}}$ reduction', loc='center')
# Define bins for diesel shares
p0 = np.nanpercentile(diesel, 0)
p33 = np.nanpercentile(diesel, 33.3)
p66 = np.nanpercentile(diesel, 66.6)
p100 = np.nanpercentile(diesel, 100)
# Small diesel shares plot
wherebin = np.where((diesel>p0)&(diesel<=p33))[0]
ensemblebin = ensemble[wherebin]
dno2bin = dno2[wherebin]
ax2.plot(ensemblebin, dno2bin, color=agpuke, marker='o', clip_on=False,
ls='none', zorder=100, label='Small diesel shares')
slope, intercept, r_value, p_value, std_err = stats.linregress(
ensemblebin, dno2bin)
ax2.plot(np.sort(ensemblebin), np.sort(ensemblebin)*slope + intercept,
ls='--', zorder=0, color=agpuke)
ax2.text(np.sort(ensemblebin)[-1]+0.25,
(np.sort(ensemblebin)*slope + intercept)[-1],
'a=%.2f,\nb=%.2f'%(slope, intercept), color=agpuke, va='center',
ha='left')
# Medium diesel shares plot
wherebin = np.where((diesel>p33)&(diesel<=p66))[0]
ensemblebin = ensemble[wherebin]
dno2bin = dno2[wherebin]
ax2.plot(ensemblebin, dno2bin, color=agred, marker='o', ls='none',
label='Medium diesel shares')
slope, intercept, r_value, p_value, std_err = stats.linregress(
ensemblebin, dno2bin)
ax2.plot(np.sort(ensemblebin), np.sort(ensemblebin)*slope + intercept,
ls='--', zorder=0, color=agred)
slope, intercept, r_value, p_value, std_err = stats.linregress(
ensemblebin, dno2bin)
ax2.plot(np.sort(ensemblebin), np.sort(ensemblebin)*slope + intercept,
ls='--', zorder=0, color=agred)
ax2.text(np.sort(ensemblebin)[-1]+0.25,
(np.sort(ensemblebin)*slope + intercept)[-1],
'a=%.2f,\nb=%.2f'%(slope, intercept), color=agred, va='center',
ha='left')
# Large diesel shares plot
wherebin = np.where((diesel>p66)&(diesel<=p100))[0]
ensemblebin = ensemble[wherebin]
dno2bin = dno2[wherebin]
ax2.plot(ensemblebin, dno2bin, color=agnavy, marker='o', ls='none',
label='Large diesel shares')
slope, intercept, r_value, p_value, std_err = stats.linregress(
ensemblebin, dno2bin)
ax2.plot(np.sort(ensemblebin), np.sort(ensemblebin)*slope + intercept,
ls='--', zorder=0, color=agnavy)
ax2.text(np.sort(ensemblebin)[-1]+0.25,
(np.sort(ensemblebin)*slope + intercept)[-1],
'a=%.2f,\nb=%.2f'%(slope, intercept), color=agnavy, va='center',
ha='left')
# Add statistical information
slope, intercept, r_value, p_value, std_err = stats.linregress(
ensemble, dno2)
txtstr = 'a=%.2f, b=%.2f\nr=%.2f\np<0.01'%(slope, intercept, r_value)
ax2.text(0.02, 0.02, txtstr, color='black', fontsize=12,
transform=ax2.transAxes, va='bottom', ha='left')
# Aesthetics
ax1.set_title('(a) Hypothesis', loc='left', fontsize=12)
ax2.set_title('(b)', loc='left', fontsize=12)
ax2.set_ylim([-70,0])
ax2.set_xlim([10, 40])
ax2.set_xticks([10, 15, 20, 25, 30, 35, 40])
ax2.set_xticklabels(['10', '15', '20', '25', '30', '35', '40'])
ax2.set_ylabel(r'$\mathregular{\Delta}$ NO$_{\mathregular{2}}$ [%]',
fontsize=12)
ax2.set_xlabel('NO$_{x,\:\mathregular{Light\u2212duty}}$ : '+\
'NO$_{x,\:\mathregular{Total}}$ [%]', loc='center', fontsize=12)
plt.subplots_adjust(left=0.05, wspace=0.40, bottom=0.2, top=0.92, right=0.95)
ax2.legend(loc=8, bbox_to_anchor=(0.5, -0.3), ncol=3, frameon=False)
plt.savefig(DIR_FIG+'fig4.pdf', dpi=1000)
return
def figS1(bcm):
"""
"""
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
# Options that work and look halfway decent are: 'GoogleTiles',
# 'GoogleWTS', 'QuadtreeTiles', 'Stamen'
request = cimgt.Stamen()
fig, axes = plt.subplots(figsize=(8.5, 11), nrows=5, ncols=3,
subplot_kw={'projection':request.crs})
axes = np.hstack(axes)
# Loop through cities for which we've built BCM/BAU concentrations
citiesunique = np.unique(bcm.City)
citiesunique = np.sort(citiesunique)
for i, city in enumerate(citiesunique[:15]):
citycoords = stationcoords.loc[stationcoords['City']==city]
# Plot station coordinates
axes[i].plot(citycoords['Longitude'], citycoords['Latitude'],
marker='o', lw=0, markersize=3, color=agred,
transform=ccrs.PlateCarree())
# Aesthetics
if ' C40' in city:
city = city[:-4]
axes[i].set_title(city, loc='left')
else:
axes[i].set_title(city, loc='left')
# Syntax is (x0, x1, y0, y1)
extent = [citycoords['Longitude'].min()-0.2,
citycoords['Longitude'].max()+0.2,
citycoords['Latitude'].min()-0.2,
citycoords['Latitude'].max()+0.2]
axes[i].set_extent(extent)
axes[i].add_image(request, 11)
axes[i].set_adjustable('datalim')
plt.subplots_adjust(left=0.03, right=0.97, top=0.97, bottom=0.03)
plt.savefig(DIR_FIG+'figS1a_lowres.pdf', dpi=600)
plt.show()
# For the rest of the focus cities
fig, axes = plt.subplots(figsize=(8.5, 11), nrows=5, ncols=3,
subplot_kw={'projection':request.crs})
axes = np.hstack(axes)
for i, city in enumerate(citiesunique[15:]):
citycoords = stationcoords.loc[stationcoords['City']==city]
axes[i].plot(citycoords['Longitude'], citycoords['Latitude'],
marker='o', lw=0, markersize=3, color=agred,
transform=ccrs.PlateCarree())
# # Add marker for Vilnius heating plant
# if city=='Vilnius':
# axes[i].plot(25.157202, 54.667939, marker='s', lw=0,
# markersize=5, color=agnavy,
# transform=ccrs.PlateCarree())
if ' C40' in city:
city = city[:-4]
axes[i].set_title(city, loc='left')
else:
axes[i].set_title(city, loc='left')
extent = [citycoords['Longitude'].min()-0.2,
citycoords['Longitude'].max()+0.2,
citycoords['Latitude'].min()-0.2,
citycoords['Latitude'].max()+0.2]
if city=='Vilnius':
extent = [citycoords['Longitude'].min()-0.1,
citycoords['Longitude'].max()+0.1,
citycoords['Latitude'].min()-0.05,
citycoords['Latitude'].max()+0.05]
request = cimgt.Stamen()
axes[i].set_extent(extent)
axes[i].add_image(request, 11)
axes[i].set_adjustable('datalim')
# Remove blank axes
for i in np.arange(7,15,1):
axes[i].axis('off')
plt.subplots_adjust(left=0.03, right=0.97, top=0.97, bottom=0.03)
plt.savefig(DIR_FIG+'figS1b_lowres.pdf', dpi=600)
plt.show()
return
def figS2():
"""
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
# Open lockdown information
sah = pd.read_csv(DIR_MOBILITY+'stay-at-home-covid.csv')
ysax1, ysax2 = [], []
pcolorax1, pcolorax2 = [], []
citiesax1, citiesax2 = [], []
cmap = plt.get_cmap('Reds')
# Plot mobility curves
fig = plt.figure(figsize=(8.5,6))
ax1 = plt.subplot2grid((2,2),(0,0), rowspan=2)
ax2 = plt.subplot2grid((2,2),(0,1), rowspan=2)
cityloc = 0
cities = []
# Loop through city DataFrame and find mobility dataset corresponding
# to each city and plot
for index, row in focuscities.iterrows():
country = row['Country']
city = row['City']
cities.append(city)
# SELECT APPLE MOBILITY
mobility_city = mobility[mobility['city'].str.contains(city)]
mobility_city.set_index('time', inplace=True)
# Select 15 January - 30 June 2020
mobility_city = mobility_city['2020-01-15':'2020-06-30']
filler = np.empty(shape=len(mobility_city))
filler[:] = cityloc+2
# SELECT STAY_HOME_REQUIREMENTS
sah_country = sah.loc[sah['Entity']==country]
sah_country.set_index('Day', inplace=True)
sah_country.index = pd.to_datetime(sah_country.index)
sah_country = sah_country['2020-01-15':'2020-06-30']
sah_country = sah_country['stay_home_requirements']
# Fill missing values
idx = pd.date_range('2020-01-15','2020-06-30')
sah_country = sah_country.reindex(idx, fill_value=np.nan)
if cityloc < 11.*2:
ax1.plot(mobility_city.index, (filler+
mobility_city['Volume'].values/100.*-1), color='k')
pcolorax1.append(sah_country.values)
ysax1.append(cityloc+1)
if ' C40' in city:
city = city[:-4]
citiesax1.append(city)
else:
ax2.plot(mobility_city.index, (filler+
mobility_city['Volume'].values/100.*-1), color='k')
pcolorax2.append(sah_country.values)
ysax2.append(cityloc+1)
if city=='Milan C40':
city='Milan'
elif city=='Santiago C40':
city='Santiago'
citiesax2.append(city)
cityloc = cityloc+2
mb = ax1.pcolormesh(sah_country.index, ysax1, np.stack(pcolorax1),
cmap=cmap, shading='auto', vmin=0, vmax=3)
mb = ax2.pcolormesh(sah_country.index, ysax2, np.stack(pcolorax2),
cmap=cmap, shading='auto', vmin=0, vmax=3)
# Aesthetics
for ax in [ax1, ax2]:
ax.set_xlim(pd.to_datetime(['2020-01-15','2020-06-30']))
ax.set_xticks(pd.to_datetime(['2020-01-15','2020-02-01', '2020-02-15',
'2020-03-01','2020-03-15','2020-04-01','2020-04-15','2020-05-01',
'2020-05-15','2020-06-01','2020-06-15']))
ax.set_xticklabels(['', 'Feb\n2020', '', 'Mar', '', 'Apr', '', 'May',
'', 'Jun', ''], fontsize=8)
plt.subplots_adjust(wspace=0.3, top=0.95, right=0.95)
ax1.set_ylim([0,ysax1[-1]+1])
ax1.set_yticks([x for x in ysax1])
ax1.set_yticklabels(citiesax1)
ax2.set_ylim([ysax2[0]-1,ysax2[-1]+1])
ax2.set_yticks([x for x in ysax2])
ax2.set_yticklabels(citiesax2)
ax1.invert_yaxis()
ax2.invert_yaxis()
legend_elements = [
Patch(facecolor=cmap(0.), edgecolor='k', label='No measures'),
Patch(facecolor=cmap(0.33), edgecolor='k', label='Recommended not '+\
'to leave the house'),
Patch(facecolor=cmap(0.66), edgecolor='k', label='Required to not '+\
'leave the house with exceptions for daily exercise, grocery '+\
'shopping, and essential trips'),
Patch(facecolor=cmap(1.), edgecolor='k', label='Required to not '+\
'leave the house with minimal exceptions (e.g., allowed to '+\
'leave only once every few days,\nor only one person can '+
'leave at a time, etc.)')]
plt.subplots_adjust(bottom=0.23, top=0.98)
ax1.legend(handles=legend_elements, loc='center', ncol=1,
bbox_to_anchor=(1.15,-0.2), frameon=False, fontsize=10)
plt.savefig(DIR_FIG+'figS2.pdf', dpi=1000)
return
def figS3():
"""
Adapted from https://matplotlib.org/2.0.2/examples/statistics/
customized_violin_demo.html
"""
fig = plt.figure(figsize=(8,4))
ax1 = plt.subplot2grid((1,3),(0,0))
ax2 = plt.subplot2grid((1,3),(0,1))
ax3 = plt.subplot2grid((1,3),(0,2))
# For MFB
ax1.hlines(0, xmin=0, xmax=4, color='darkgrey', ls='--', lw=2, zorder=0)
parts1 = ax1.violinplot([mfborig, mfbtrain, mfbvalid], showmeans=False,
showmedians=False, showextrema=False)
# Add medians
ax1.hlines(np.median(mfborig), 0.95, 1.05, color='w', linestyle='-', lw=2,
zorder=10)
ax1.hlines(np.median(mfbvalid), 2.95, 3.05, color='w', linestyle='-', lw=2,
zorder=10)
for i, mfbi in enumerate([mfborig, mfbtrain, mfbvalid]):
q1, medians, q3 = np.percentile(mfbi, [25, 50, 75])
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, np.sort(mfbi)[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, np.sort(mfbi)[0], q1)
# if i!=1:
# ax1.scatter(i+1, medians, marker='o', color='white', s=30, zorder=3)
ax1.vlines(i+1, q1, q3, color='k', linestyle='-', lw=5)
ax1.vlines(i+1, lower_adjacent_value, upper_adjacent_value, color='k',
linestyle='-', lw=1)
# For r
ax2.hlines(1, xmin=0, xmax=4, color='darkgrey', ls='--', lw=2, zorder=0)
parts2 = ax2.violinplot([rorig, rtrain, rvalid], showmeans=False,
showmedians=False, showextrema=False)
ax2.hlines(np.median(rorig), 0.95, 1.05, color='w', linestyle='-', lw=2,
zorder=10)
ax2.hlines(np.median(rtrain), 1.95, 2.05, color='w', linestyle='-', lw=1,
zorder=10)
ax2.hlines(np.median(rvalid), 2.95, 3.05, color='w', linestyle='-', lw=2,
zorder=10)
for i, r in enumerate([rorig, rtrain, rvalid]):
q1, medians, q3 = np.percentile(r, [25, 50, 75])
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, np.sort(r)[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, np.sort(r)[0], q1)
ax2.vlines(i+1, q1, q3, color='k', linestyle='-', lw=5)
ax2.vlines(i+1, lower_adjacent_value, upper_adjacent_value, color='k', linestyle='-', lw=1)
# F2F
ax3.hlines(1, xmin=0, xmax=4, color='darkgrey', ls='--', lw=2, zorder=0)
parts3 = ax3.violinplot([fac2orig, fac2train, fac2valid], showmeans=False,
showmedians=False, showextrema=False)
ax3.hlines(np.median(fac2orig), 0.95, 1.05, color='w', linestyle='-', lw=2,
zorder=10)
ax3.hlines(np.median(fac2valid), 2.95, 3.05, color='w', linestyle='-', lw=2,
zorder=10)
for i, fac2 in enumerate([fac2orig, fac2train, fac2valid]):
q1, medians, q3 = np.percentile(fac2, [25, 50, 75])
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, np.sort(fac2)[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, np.sort(fac2)[0], q1)
ax3.vlines(i+1, q1, q3, color='k', linestyle='-', lw=5)
ax3.vlines(i+1, lower_adjacent_value, upper_adjacent_value, color='k', linestyle='-', lw=1)
for parts in [parts1, parts2, parts3]:
for i, pc in enumerate(parts['bodies']):
if i==0:
pc.set_facecolor(agnavy)
elif i==1:
pc.set_facecolor(agorange)
else:
pc.set_facecolor(agpuke)
pc.set_edgecolor('black')
pc.set_alpha(1)
# Aesthetics
ax1.set_title('(a) Mean fraction bias', loc='left')
ax2.set_title('(b) Correlation coefficient', loc='left')
ax3.set_title('(c) Factor-of-2 fraction', loc='left')
for ax in [ax1, ax2, ax3]:
ax.set_xticks([1,2,3])
ax.set_xticklabels(['GEOS-CF', '\nTraining', '\nTesting'], fontsize=9)
ax.text(0.43, -0.055, 'Business-as-usual', transform=ax.transAxes,
fontsize=9)
ax.tick_params(labelsize=9)
ax.set_xlim([0.5, 3.5])
ax1.set_ylim([-1.5, 0.5])
ax2.set_ylim([-0.2, 1.01])
ax3.set_ylim([0., 1.01])
plt.subplots_adjust(left=0.07, right=0.95, wspace=0.26)
plt.savefig(DIR_FIG+'figS3.pdf', dpi=1000)
return
def figS4():
import datetime as dt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
sys.path.append('/Users/ghkerr/GW/mobility/')
import readc40mobility
focuscities = build_focuscities(True)
import math