-
Notifications
You must be signed in to change notification settings - Fork 0
/
lorenz_curve.py
3663 lines (3082 loc) · 153 KB
/
lorenz_curve.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
# This contains lorenz curve functions to measure equity of different resiliency functions
import numpy as np
import networkx as nx
import osmnx as ox
import pandas as pd
import geopandas as gpd
import math
from matplotlib import pyplot as plt
import matplotlib
from matplotlib import patches
from matplotlib.lines import Line2D
from scipy.interpolate import make_interp_spline
import network_analysis_base as mynet
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
# set font family
plt.rcParams['font.family'] = "ubuntu"
# filepath variables
network_data_fp = '/media/mdp0023/extradrive1/Data/Network_Data/Austin_North'
svi_data_fp = '/home/mdp0023/Documents/Codes_Projects/SVI_Code/Travis_County'
graphs_fp = '/media/mdp0023/extradrive1/Data/Network_Data/Austin_North/AN_Graphs'
# Load variables
# SVI Shapefile: specific to 2015, relevant to the flood
svi = gpd.read_file(f'{svi_data_fp}/SVI_Shapefiles/Travis_county_svi_2015_selected.shp')
# read in background network, convert eges to shapefile
# BUG: has to be no TA network
# network = mynet.read_graph_from_disk(path=f'{network_data_fp}/AN_Graphs',
# name='AN_Graph_2015052522_inundation')
network = mynet.read_graph_from_disk(path=f'{network_data_fp}/AN_Graphs',
name='AN_Graph_2015052518_inundation')
gdf_edges = ox.graph_to_gdfs(G=network, nodes=False)
# Read in the TA parcels
# res_parcels = gpd.read_file(f'{network_data_fp}/AN_Graphs/Flow_decomp/2015052522_inundation_res_parcel_flow_decomp.shp')
res_parcels = gpd.read_file(f'{network_data_fp}/AN_Graphs/Flow_decomp/2015052518_inundation_res_parcel_flow_decomp.shp')
# Read in 2015 specific socio-demographic variables, grab relevent variables data and merge with SVI
vars2015 = pd.read_csv(f'{svi_data_fp}/Calculated_Variables/Travis_county_var_2015.csv')
vars2015=vars2015[['PPUNIT','GEOID']].copy()
svi=svi.merge(vars2015,left_on='GEOID', right_on='GEOID')
# figure size converstion
mm=1/25.4
##############################################################################################################################################
# FUNCTIONS
# Gini coefficent
def gini(arr):
"""
Calculates the Gini coefficient.
A Gini coefficeint is the measure deviation the lorenz curve has from a perfectly equitable (1:1) relationship
:param arr: list of values, sorted from lowest to highest SVI (or whatever independent variable is being analyzed)
:type arr: np.array
:returns:
- **gini**, Value of deviation between lorenz curve and line of perfect equity
:rtype: float
"""
# arr should already be sorted how we want it
sorted_arr = arr.copy()
n = arr.size
coef_ = 2. / n
const_ = (n + 1.) / n
weighted_sum = sum([(i+1)*yi for i, yi in enumerate(sorted_arr)])
return coef_*weighted_sum/(sorted_arr.sum()) - const_
# example lorenz curve for presentations
def example_lorenz():
"""
Plots a descriptive example of a lorenz curve with appropraite annotations. This isn't meant to plot any real data, just a presentation quality example.
returns: matplotlib fig
"""
# set figure titles
fig, ax = plt.subplots(figsize=[5, 5])
fig.set_facecolor('none')
fig.supxlabel('Social Vulnerability Index Percentile',
weight='bold',
x=0.5,
fontsize=16)
fig.supylabel('Normalized Cumulative Sum of Variable',
weight='bold',
fontsize=16)
# Plot perfect equity line
eq_line, = ax.plot([0, 1], [0, 1], color='k',
linestyle='--', label='Equality Line')
# Set x and y tick markers
ax.set_xticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=[
'0%', '25%', '50%', '75%', '100%'], fontsize=14)
ax.set_yticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=[
'0%', '25%', '50%', '75%', '100%'], fontsize=14)
# set x and y limits
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
# function to plot curve
def hanging_line(point1, point2):
import numpy as np
a = (point2[1] - point1[1])/(np.cosh(point2[0]) - np.cosh(point1[0]))
b = point1[1] - a*np.cosh(point1[0])
x = np.linspace(point1[0], point2[0], 100)
y = a*np.cosh(x) + b
return (x, y)
point1 = [0, 0]
point2 = [1, 1]
x, y = hanging_line(point1, point2)
ax.plot(x, y, color='red', linewidth=2, label='Lorenz Curve')
# annotation value
val1 = gini(x)
# annotation box text
textstr = '\n'.join((f'Gini: {round(val1,4)}',))
# patch properties
props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
# text box in upper left in axes coords
ax.text(0.025, 0.975,
textstr,
transform=ax.transAxes,
fontsize=14,
verticalalignment='top',
bbox=props)
# add proportion of weight annotations
# find the 25th and 75th percentile
perc_25 = np.percentile(y, 25)
perc_50 = np.percentile(y, 50)
perc_75 = np.percentile(y, 75)
# plot vertical and horizontal lines for these locations
perc_25_line_v, = ax.plot(
[0.25, 0.25], [0, perc_25], color='dimgray', linestyle='dotted')
perc_25_line_h, = ax.plot(
[0, 0.25], [perc_25, perc_25], color='dimgray', linestyle='dotted')
perc_50_line_v, = ax.plot(
[0.50, 0.50], [0, perc_50], color='dimgray', linestyle='dotted')
perc_50_line_h, = ax.plot(
[0, 0.50], [perc_50, perc_50], color='dimgray', linestyle='dotted')
perc_75_line_v, = ax.plot(
[0.75, 0.75], [0, perc_75], color='dimgray', linestyle='dotted')
perc_75_line_h, = ax.plot(
[0, 0.75], [perc_75, perc_75], color='dimgray', linestyle='dotted')
# Plot double arrow annotations
arrow1 = patches.FancyArrowPatch((0.025, 0), (0.025, perc_25),
arrowstyle='<->',
mutation_scale=10,
color='dimgray')
arrow2 = patches.FancyArrowPatch((0.2, perc_25), (0.2, perc_50),
arrowstyle='<->',
mutation_scale=10,
color='dimgray')
arrow3 = patches.FancyArrowPatch((0.45, perc_50), (0.45, perc_75),
arrowstyle='<->',
mutation_scale=10,
color='dimgray')
arrow4 = patches.FancyArrowPatch((0.65, perc_75), (0.65, 1),
arrowstyle='<->',
mutation_scale=10,
color='dimgray')
ax.add_patch(arrow1)
ax.add_patch(arrow2)
ax.add_patch(arrow3)
ax.add_patch(arrow4)
# Plot percentage values
ax.annotate(text=f'{round(perc_25*100)}%',
xy=(0.06, perc_25/2-0.01), fontsize=14)
ax.annotate(text=f'{round((perc_50-perc_25)*100)}%',
xy=(0.2, (perc_50-perc_25)/2+perc_25), fontsize=14)
ax.annotate(text=f'{round((perc_75-perc_50)*100)}%',
xy=(0.46, (perc_75-perc_50)/2+perc_50), fontsize=14)
ax.annotate(text=f'{round((1-perc_75)*100)}%',
xy=(0.67, (1-perc_75)/2+perc_75), fontsize=14)
# add table
col_labels = ['Q1', 'Q2', 'Q3', 'Q4']
row_labels = ['Lorenz']
table_vals = [[f'{round(perc_25*100)}%',
f'{round((perc_50-perc_25)*100)}%',
f'{round((perc_75-perc_50)*100)}%',
f'{round((1-perc_75)*100)}%']]
the_table = ax.table(cellText=table_vals, colWidths=[0.13]*4,
rowColours=['r'],
rowLabels=row_labels,
colLabels=col_labels,
colColours=['lightgray', 'lightgray',
'lightgray', 'lightgray'],
loc='lower right')
the_table.auto_set_font_size(False)
the_table.set_fontsize(14)
the_table.set_zorder(100)
the_table.scale(1, 1.5)
plt.tight_layout()
plt.show()
return fig
# Single basic Lorenz curve: isn't actually called anywhere, either remove, or modify other functions to call this
def lorenz_curve(X):
"""
Creates a Lorenz curve plot.
Creates Lorenz curve plot based on given datasets of ordered variables.
:param X: list of values, sorted from lowest to highest SVI (or whatever independent variable is being analyzed)
:type X: np.array
:returns:
- **lorenz plot**, figure showing equitable/inequitable distribution of a variable across a population
:rtype: matplotlib fig
"""
lorenz = X.cumsum() / X.sum()
lorenz = np.insert(lorenz, 0, 0)
vals = np.arange(lorenz.size)/(lorenz.size-1)
fig, ax = plt.subplots(figsize=[6, 6])
# Equality line
eq_line, = ax.plot([0, 1], [0, 1], color='k',
linestyle='--', label='Equality Line')
lorenz_plot, = ax.plot(vals, lorenz, label='tsamp', color='red')
plt.title("Lorenz Curve")
ax.set_xlabel("Independent Variable (i.e., ordered SVI")
ax.set_ylabel("Impact Variable")
# add legend
ax.legend(handles=[eq_line, lorenz_plot], loc='lower right')
# add annotation box
# annotation value
val1 = gini(X)
# annotation box text
textstr = '\n'.join((f'Gini: {round(val1,4)}',))
# patch properties
props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
# text box in upper left in axes coords
ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
verticalalignment='top', bbox=props)
# Lorenz curve multiplot: also not called???
def lorenz_curve_multiplot(X, row, column, axes, idx, names, method, annotations, tstamp=False):
"""
Manipulates existing instances of a matplotlib figure and axes to plot multiple lorenz curves on a single figure.
Each time this function is called, it manipulates a different subplot within an existing instance of a figure created from matplotlib.subplots
:param X: list of values, sorted from lowest to highest SVI (or whatever independent variable is being analyzed)
:type X: np.array
:param row: row number within existing figure
:type row: int
:param col: column number within existing figure
:type col: int
:param axes: axes within the figure being manipulated
:type axes: array of matplotlib.axes
:param idx: number used to call elements from names, the "plot number" within the figure
:type idx: int
:param names: the name that gets plotted with each subplot (e.g., the resource names)
:type names": list of strings
:param method: the x-axis variable, one of the following: 'SVI_scaled', 'Factor 1', 'Factor 2', determines plotting color
:type method: string
:param tstamp: if True, plots time series data for each subplot, and adjusts colors accordingly
:type tstamp: bool
inputs:
X: np.array, in the order of lowest to highest SVI
row: int, row number of plot
col: int, col number of plot
axes: axes of function
idx: enumerate number of plot
names: list of names of the resources
method: x axis, should be 'SVI_scaled', 'Factor 1', or 'Factor 2', used only to determine line color
tstamp: if False, just use normal red,blue, green, if not False, select appropriate value
"""
# set plot color based on method
if method == 'SVI_scaled':
if tstamp is False:
c_line='red'
else:
colors = ['#ffffcc', '#ffeda0', '#fed976', '#feb24c',
'#fd8d3c', '#fc4e2a', '#e31a1c', '#bd0026', '#800026']
c_line = colors[tstamp]
elif method == 'Factor 1':
if tstamp is False:
c_line='blue'
else:
colors = ['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb',
'#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58']
c_line = colors[tstamp]
elif method == 'Factor 2':
if tstamp is False:
c_line='green'
else:
colors = ['#ffffe5', '#f7fcb9', '#d9f0a3', '#addd8e',
'#78c679', '#41ab5d', '#238443', '#006837', '#004529']
c_line = colors[tstamp]
lorenz = X.cumsum() / X.sum()
lorenz = np.insert(lorenz, 0, 0)
val = np.arange(lorenz.size)/(lorenz.size-1)
# Equality line
eq_line, = axes[row,column].plot([0, 1], [0, 1], color='k',linestyle='--', label='Equality Line')
# lorenze curve
lorenz_plot, = axes[row,column].plot(val, lorenz, label='tsamp', color=c_line, linewidth=2)
# set title to resource name
axes[row,column].set_title(names[idx], style='italic')
# Set x and y tick markers
axes[row, column].set_xticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=['0%','25%','50%','75%','100%'])
axes[row, column].set_yticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=['0%', '25%', '50%', '75%', '100%'])
# set x and y limits
axes[row, column].set_xlim(0,1)
axes[row, column].set_ylim(0,1)
if annotations is True:
# add annotation box
# annotation value
val1 = gini(X)
# annotation box text
textstr = '\n'.join((f'Gini: {round(val1,4)}',))
# patch properties
props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
# text box in upper left in axes coords
axes[row,column].text(0.025, 0.975,
textstr,
transform=axes[row,column].transAxes,
fontsize=10,
verticalalignment='top',
bbox=props)
# add proportion of weight annotations
# find the 25th and 75th percentile
perc_25=np.percentile(lorenz,25)
perc_75=np.percentile(lorenz,75)
# plot vertical and horizontal lines for these locations
perc_25_line_v, = axes[row, column].plot([0.25, 0.25], [0, perc_25], color='dimgray', linestyle='dotted')
perc_25_line_h, = axes[row, column].plot([0, 0.25], [perc_25, perc_25], color='dimgray',linestyle='dotted')
perc_75_line_v, = axes[row, column].plot([0.75, 0.75], [0, perc_75], color='dimgray',linestyle='dotted')
perc_75_line_h, = axes[row, column].plot([0, 0.75], [perc_75, perc_75], color='dimgray',linestyle='dotted')
# Plot double arrow annotations
arrow1 = patches.FancyArrowPatch((0.025, 0), (0.025, perc_25),
arrowstyle='<->',
mutation_scale=10,
color='dimgray')
arrow2 = patches.FancyArrowPatch((0.2, perc_25), (0.2, perc_75),
arrowstyle='<->',
mutation_scale=10,
color='dimgray')
arrow3 = patches.FancyArrowPatch((0.45, perc_75), (0.45, 1),
arrowstyle='<->',
mutation_scale=10,
color='dimgray')
axes[row,column].add_patch(arrow1)
axes[row,column].add_patch(arrow2)
axes[row,column].add_patch(arrow3)
# Plot percentage values
axes[row,column].annotate(text=f'{round(perc_25*100)}%',xy=(0.025,perc_25+.01))
axes[row,column].annotate(text=f'{round((perc_75-perc_25)*100)}%',xy=(0.07,(perc_75-perc_25)/2+perc_25))
axes[row,column].annotate(text=f'{round((1-perc_75)*100)}%', xy=(0.3, (1-perc_75)/2+perc_75))
# Network reliability, impacted roads Lorenz curve
def network_reliability(axes,
fpath,
prefix,
svi,
method='SVI_scaled',
variable='agr_no_cap',
times=[],
annotations=True,
columns=3,
ftypes=['inundation']):
"""
Function to plot lorenz curve of impact on roads with options to show compound, fluvial, and/or pluvial impacts in time series or not.
This should automate the creation of network reliability lorenz curves, with a highly customizable plot tool. Some important usage notes:
fpath and prefix:
- used to find the graphs that need to be analyzed
- graphs should have the following naming convention: {fpath}/{prefix}_{time}_{ftype}, matching the 'times' and 'ftypes' inputs
method:
-the x-axis variable the Lorenz curve is plotted against
-acceptable values: 'SVI_scaled', 'Factor 1', or 'Factor 2' (refers to attributes of svi geodataframe)
-Currently, Factor 2 is inversed, because it is the economic factor (inversely related to vulnerability)
-TODO: should be a seperate function method to allow input on whether variable is inversed or not
variable:
- The y-axis varaible being plotted. The acceptable values and their meaning are as follows:
-'agr_no_cap': aggressive inundation, number of roads with no capacity per block group
-'perc_no_cap': aggressive inundation, percentage of roads with no capacity per block group
-'agr_increased_travel_time': aggresive inundation, number of roads with an increased travel time per block group
-'perc_increased_travel_time': aggressive inundation, percentage of roads with an increased travel time per block group
-'agr_impact': aggressive inundation, number of roads impacted (increased travel time & no capacity) per block group
-'perc_perc_impact':aggressive inundation, percentage of roads impacted (increased travel time & no capacity per block group)
-default: 'agr_no_cap'
- regardless of the variable, it is also weighted by PPUNIT (people per unit) Census data, to account for population density differences
times:
- should be in the format YYYYMMDDHH
- used to plot subplot titles as well as point to which network needs to be loaded
columns:
- the number of columns in the figure, used to iterate through plotting
ftypes:
- Which floods should be considered, list of strings
- Acceptable values are 'inundation' for compound, 'inundation_fluvial' for fluvial, and 'inundation_pluvial' for pluvial
:param axes: axes of figure being manipulated. If only plotting a single instance, put axes in [[]]
:type axes: array of matplotlib.axes
:param fpath: the folder path where the graphs are stored
:type fpath: string
:param prefix: the graph network prefixes
:type prefix: string
:param method: the x-axis variable
:type method: string
:param variable: y-axis variable
:type variable: string
:param times: the times associated with each network to be loaded and analyzed
:type times: list of strings
:param annotations: If True, plots annotation box containing quartile burden information and Gini coefficients
:type annotations: bool
:param columns: number of columns in figure being manipulated
:type columns: int
:param ftypes: which flood types should be plotted
:type ftypes: list of strings
"""
column = 0
row = 0
# read in appropriate network and convert to geopandas dataframe
for a, time in enumerate(times):
# create variable to hold information for percentile table
table_vals = [[0, 0, 0, 0] for _ in range(len(ftypes))]
# create a variable to hold information regarding gini coefficeints
ginis = [0 for _ in range(len(ftypes))]
# for each flood type of interest
for b, ftype in enumerate(ftypes):
network = mynet.read_graph_from_disk(path=fpath,
name=f'{prefix}_{time}_{ftype}')
gdf_edges = ox.graph_to_gdfs(G=network, nodes=False)
# spatial join
sjoined_data = gpd.sjoin(left_df=svi,
right_df=gdf_edges,
how='left')
# count the number of roads within each block group and relate back to svi geodataframe
count_dict = sjoined_data['GEOID'].value_counts().to_dict()
svi["count"] = svi["GEOID"].apply(lambda x: count_dict.get(x))
# count the number of roads within each block group with 0 capacity under agressive flood relationship
subset_df = sjoined_data.loc[sjoined_data['inundation_capacity_agr'] == 0]
count_dict = subset_df['GEOID'].value_counts().to_dict()
svi["agr_no_cap"] = svi["GEOID"].apply(lambda x: count_dict.get(x))
svi['agr_no_cap'] = svi['agr_no_cap'].fillna(0)
# count the number of roads within each block group with an increased travel time under agressive flood relationship
subset_df = sjoined_data.loc[sjoined_data['inundation_travel_time_agr']
> sjoined_data['travel_time']]
count_dict = subset_df['GEOID'].value_counts().to_dict()
svi["agr_increased_travel_time"] = svi["GEOID"].apply(
lambda x: count_dict.get(x))
svi['agr_increased_travel_time'] = svi['agr_increased_travel_time'].fillna(
0)
# count the number of roads impacted (increased travel time & 0 capacity)
svi['agr_impact'] = svi['agr_increased_travel_time'] + svi['agr_no_cap']
# calc percentage of roads within a BG with no capacity
svi['perc_no_cap'] = svi['agr_no_cap']/svi['count']*100
# calc percentage of roads within a BG with an increased travel time
svi['perc_increased_travel_time'] = svi['agr_increased_travel_time'] / \
svi['count']*100
# calc percentage of roads within a BG impacted
svi['perc_impact'] = svi['agr_impact']/svi['count']*100
# sort svi dataframe by appropriate column
if method == 'Factor 2':
svi.sort_values('Factor 2', axis=0,
inplace=True, ascending=False)
else:
svi.sort_values(method, axis=0, inplace=True, ascending=True)
# TODO: weight value by PPUNIT
svi[variable] = svi[variable]*svi["PPUNIT"]
# LORENZ CURVE
# extract values to use in Lorenz curve
if method == 'Factor 2':
array = svi[variable].values*-1
else:
array = svi[variable].values
# calculate lorenz values
lorenz = array.cumsum() / array.sum()
lorenz = np.insert(lorenz, 0, 0)
val = np.arange(lorenz.size)/(lorenz.size-1)
if ftype == 'inundation':
c_line = '#cc57a4'
elif ftype == 'inundation_pluvial':
c_line = '#ff772e'
elif ftype == 'inundation_fluvial':
c_line = '#216aa6'
# lorenze curve
lorenz_plot, = axes[row][column].plot(val, lorenz, label='tsamp', color=c_line, linewidth=2)
perc_25 = np.percentile(lorenz, 25)
perc_50 = np.percentile(lorenz, 50)
perc_75 = np.percentile(lorenz, 75)
table_vals[b][0] = f'{round(perc_25*100)}%'
table_vals[b][1] = f'{round(perc_50*100)-round(perc_25*100)}%'
table_vals[b][2] = f'{round(perc_75*100)-round(perc_50*100)}%'
table_vals[b][3] = f'{100-round(perc_75*100)}%'
# calc gini and save
ginis[b] = gini(array)
col_labels = ['Q1', 'Q2', 'Q3', 'Q4']
# determine appropriate row labels
row_labels = []
for ftype in ftypes:
if ftype == 'inundation':
row_labels.append('Cmpd.')
elif ftype == 'inundation_fluvial':
row_labels.append('Fluvial')
elif ftype == 'inundation_pluvial':
row_labels.append('Pluvial')
# determine appropriate row colors
row_colors=[]
for ftype in ftypes:
if ftype == 'inundation':
row_colors.append('#cc57a4')
elif ftype == 'inundation_fluvial':
row_colors.append('#216aa6')
elif ftype == 'inundation_pluvial':
row_colors.append('#ff772e')
# the rectangle is where I want to place the table
if annotations is True:
# plot ginis
textstr = []
for i, row_label in enumerate(row_labels):
textstr.append(f'{row_label} G: {round(ginis[i],2)}')
textstr = '\n'.join(textstr)
# Gini patch properties
props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
# text box in upper left in axes coords
axes[row][column].text(0.05, 0.95, textstr, transform=axes[row][column].transAxes, fontsize=8,
verticalalignment='top', bbox=props)
# Plot quartile information
the_table = axes[row][column].table(cellText=table_vals,
# colWidths=[0.10]*4,
rowColours=row_colors,
colColours=['lightgrey', 'lightgrey',
'lightgrey', 'lightgrey'],
rowLabels=row_labels,
colLabels=col_labels,
loc='bottom')
the_table.auto_set_font_size(False)
the_table.set_fontsize(8)
the_table.scale(1, 0.8)
# Equality line
eq_line, = axes[row][column].plot(
[0, 1], [0, 1], color='k', linestyle='--', label='Equality Line')
# Set x and y tick markers
axes[row][column].set_xticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=[' ', ' ', ' ', ' ', ' '])
#labels=[' ', '25%', '50%', '75%', '100%'])
axes[row][column].set_yticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0],
labels=['0%', '25%', '50%', '75%', '100%'])
# adjust ticks
axes[row][column].tick_params(axis="x", direction="in")
# set x and y limits
axes[row][column].set_xlim(0, 1)
axes[row][column].set_ylim(0, 1)
# set axes title
axes[row][column].set_title(
f'{time[-2:]}:00 {time[6:8]}/{time[4:6]}/{time[:4]}', style='italic')
# update row and column names
column += 1
if column == columns:
column = 0
row += 1
# Individual reliability, cost to access resources Lorenz curve
def individual_reliability(axes,
cost_atrs,
res_names,
svi,
res_parcels,
methods=['SVI_scaled'],
weight=4,
aggregate=True,
annotations=True,
columns=3):
"""
Function to plot Lorenz curves of individual reliability for resource accessibility, analyzing the cost to access resources. Some important usage notes:
cost_atrs:
- this is a list of strings associated with the res_parcels geodataframe attributes that are the variables of interest. They should be the attributes that represent the cost to access each resource.
- each variable is weighted by the PPUNIT Census variable to account for population density differences
res_names:
- These are the real resource names associated with each cost attribute variable in the same order.
methods:
-the x-axis variable the Lorenz curve is plotted against
-acceptable values: 'SVI_scaled', 'Factor 1', and/or 'Factor 2' (refers to attributes of svi geodataframe)
-Currently, Factor 2 is inversed, because it is the economic factor (inversely related to vulnerability)
-TODO: should be a seperate function method to allow input on whether variable is inversed or not
outlier masking:
- Due to the occurance of severe outliers occuring in travel times, (e.g., a residential parcel located at the end of a long roadway that has an extremely high travel time), the cost to access resources are "projected" onto a feasible set. This is done by calculating the interquartile range (IQR). A value is considered an outlier if it is equal to or greater than 3 times the IQR. These values are set to be equal to 3*IQR.
:param axes: axes of figure being manipulated
:type axes: array of matplotlib.axes
:param cost_atrs: the attributes within the res_parcels geodataframe that need to be considered
:type cost_atrs: list of strings
:param res_names: the names associated with each element in cost_atrs (i.e., the resources actual name)
:type res_names: list of strings
:param svi: the social vulnerabilty dataset to aggregate results to
:type svi: geodataframe
:param res_parcels: the residential parcels with flow decomposition information (i.e., the cost to get to each resource type)
:type res_parcels: geodataframe
:param methods: the x-axis variable
:type methods: list of strings
:param weight: weight to apply to parcels that cannot access the resource. The value will be set to the maximum travel time for that resource times weight
:type weight: int
:param aggregate: if True, also plots an aggregate Lorenz curve.
:type aggregate: bool
:param annotations: If True, plots annotation box containing quartile burden information and Gini coefficients
:type annotations: bool
:param columns: number of columns in figure being manipulated
:type columns: int
"""
column = 0
row = 0
# create blank array of all_arrays for the aggregate calcuation
if aggregate is True:
all_arrays = [np.zeros_like(svi.shape[0], dtype='float') for _ in range(len(methods))]
# Reproject cost of acces values into a "feasible set"
# removing the impact of outliers by setting them all equal to the 3rd quantile plus 3*the IQR
for cost_atr in cost_atrs:
# # IQR METHOD to mask impact of outliers
costs = sorted(res_parcels[cost_atr].tolist())
costs = [x for x in costs if math.isnan(x) == False]
q1, q3, = np.percentile(costs, [25, 75])
iqr = q3-q1
upper_bound = q3+(3*iqr)
res_parcels.loc[res_parcels[cost_atr] >=
upper_bound, [cost_atr]] = upper_bound
# BEGIN MAIN LOOP
# for each resource,
for idx, cost_atr in enumerate(cost_atrs):
# create variable to hold information for percentile table
table_vals = [[0, 0, 0, 0] for _ in range(len(methods))]
# create a variable to hold information regarding gini coefficeints
ginis = [0 for _ in range(len(methods))]
# for each method,
for b, method in enumerate(methods):
# Spatial join
sjoined_data = gpd.sjoin(left_df=svi,
right_df=res_parcels,
how='left')
# Fill nans with maximum from that column, and return back to GeoDataFrame
filled_data = sjoined_data[cost_atr].replace(np.nan, sjoined_data[cost_atr].max()*weight)
sjoined_data[cost_atr] = filled_data
# count the number of residential parcels within each block group and relate back to geodataframe
count_dict = sjoined_data['GEOID'].value_counts().to_dict()
sjoined_data["count"] = sjoined_data["GEOID"].apply(
lambda x: count_dict.get(x))
# Aggregate results
summed_gdf = sjoined_data.dissolve(by='GEOID', aggfunc={cost_atr: 'sum',
'SVI_scaled': 'first',
'Factor 1': 'first',
'Factor 2': 'first',
'PPUNIT': 'first',
'count': 'first'})
# TODO: create ppunit AND/OR count weighted column
summed_gdf[cost_atr] = summed_gdf[cost_atr]*summed_gdf["PPUNIT"]
# SORT BY appropriate column
if method == 'Factor 2':
summed_gdf.sort_values(
method, axis=0, inplace=True, ascending=False)
else:
summed_gdf.sort_values(method, axis=0, inplace=True)
# TODO: HAVE TO MULTIPLY ARRAY by -1 IF FACTOR 2 DUE TO INVERSE WEALTH
# single resource specific flood conditions
if method == 'Factor 2':
array = summed_gdf[cost_atr].values*-1
else:
array = summed_gdf[cost_atr].values
# aggregate all arrays for combined lorenz
if aggregate is True:
all_arrays[b] = np.add(array, all_arrays[b])
# calculate lorenz values
lorenz = array.cumsum() / array.sum()
lorenz = np.insert(lorenz, 0, 0)
val = np.arange(lorenz.size)/(lorenz.size-1)
if method == 'SVI_scaled':
c_line = 'r'
elif method == 'Factor 1':
c_line = 'b'
elif method == 'Factor 2':
c_line = 'g'
# lorenze curve
lorenz_plot, = axes[row][column].plot(
val, lorenz, label='tsamp', color=c_line, linewidth=2)
perc_25 = np.percentile(lorenz, 25)
perc_50 = np.percentile(lorenz, 50)
perc_75 = np.percentile(lorenz, 75)
table_vals[b][0] = f'{round(perc_25*100)}%'
table_vals[b][1] = f'{round(perc_50*100)-round(perc_25*100)}%'
table_vals[b][2] = f'{round(perc_75*100)-round(perc_50*100)}%'
table_vals[b][3] = f'{100-round(perc_75*100)}%'
# calc gini and save
ginis[b] = gini(array)
col_labels = ['Q1', 'Q2', 'Q3', 'Q4']
# determine appropriate row labels
row_labels = []
for method in methods:
if method == 'SVI_scaled':
row_labels.append('SVI')
elif method == 'Factor 1':
row_labels.append('SS')
elif method == 'Factor 2':
row_labels.append('ES')
# determine appropriate row colors
row_colors=[]
for method in methods:
if method == 'SVI_scaled':
row_colors.append('r')
elif method == 'Factor 1':
row_colors.append('b')
elif method == 'Factor 2':
row_colors.append('g')
# the rectangle is where I want to place the table
if annotations is True:
# plot ginis
textstr = []
for i, row_label in enumerate(row_labels):
textstr.append(f'{row_label} Gini: {round(ginis[i],2)}')
textstr = '\n'.join(textstr)
# Gini patch properties
props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
# text box in upper left in axes coords
axes[row][column].text(0.05, 0.95, textstr, transform=axes[row][column].transAxes, fontsize=10,
verticalalignment='top', bbox=props)
# Plot quartile information
the_table = axes[row][column].table(cellText=table_vals,
colWidths=[0.10]*4,
rowColours=row_colors,
colColours=['lightgrey', 'lightgrey',
'lightgrey', 'lightgrey'],
rowLabels=row_labels,
colLabels=col_labels,
loc='lower right')
the_table.auto_set_font_size(False)
the_table.set_fontsize(10)
the_table.scale(1, 1)
for i, val in enumerate(methods):
the_table[i+1,-1].get_text().set_color('white')
# Equality line
eq_line, = axes[row][column].plot(
[0, 1], [0, 1], color='k', linestyle='--', label='Equality Line')
# Set x and y tick markers
axes[row][column].set_xticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=[
'0%', '25%', '50%', '75%', '100%'])
axes[row][column].set_yticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=[
'0%', '25%', '50%', '75%', '100%'])
# set x and y limits
axes[row][column].set_xlim(0, 1)
axes[row][column].set_ylim(0, 1)
# set axes title
axes[row][column].set_title(res_names[idx],style='italic')
# update row and column names
column += 1
if column == columns:
column = 0
row += 1
if aggregate is True:
# create variable to hold information for percentile table
table_vals = [[0, 0, 0, 0] for _ in range(len(methods))]
# create a variable to hold information regarding gini coefficeints
ginis = [0 for _ in range(len(methods))]
for b, method in enumerate(methods):
# calculate lorenz values
lorenz = all_arrays[b].cumsum() / all_arrays[b].sum()
lorenz = np.insert(lorenz, 0, 0)
val = np.arange(lorenz.size)/(lorenz.size-1)
if method == 'SVI_scaled':
c_line = 'r'
elif method == 'Factor 1':
c_line = 'b'
elif method == 'Factor 2':
c_line = 'g'
# lorenze curve
lorenz_plot, = axes[row][column].plot(
val, lorenz, label='tsamp', color=c_line, linewidth=2)
perc_25 = np.percentile(lorenz, 25)
perc_50 = np.percentile(lorenz, 50)
perc_75 = np.percentile(lorenz, 75)
table_vals[b][0] = f'{round(perc_25*100)}%'
table_vals[b][1] = f'{round(perc_50*100)-round(perc_25*100)}%'
table_vals[b][2] = f'{round(perc_75*100)-round(perc_50*100)}%'
table_vals[b][3] = f'{100-round(perc_75*100)}%'
# calc gini and save
ginis[b] = gini(all_arrays[b])
col_labels = ['Q1', 'Q2', 'Q3', 'Q4']
# determine appropriate row labels
row_labels = []
for method in methods:
if method == 'SVI_scaled':
row_labels.append('SVI')
elif method == 'Factor 1':
row_labels.append('SS')
elif method == 'Factor 2':
row_labels.append('ES')
# determine appropriate row colors
row_colors = []
for method in methods:
if method == 'SVI_scaled':
row_colors.append('r')
elif method == 'Factor 1':
row_colors.append('b')
elif method == 'Factor 2':
row_colors.append('g')
# the rectangle is where I want to place the table
if annotations is True:
# plot ginis
textstr = []
for i, row_label in enumerate(row_labels):
textstr.append(f'{row_label} Gini: {round(ginis[i],2)}')
textstr = '\n'.join(textstr)
# Gini patch properties
props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
# text box in upper left in axes coords
axes[row][column].text(0.05, 0.95, textstr, transform=axes[row][column].transAxes, fontsize=10,
verticalalignment='top', bbox=props)
# Plot quartile information
the_table = axes[row][column].table(cellText=table_vals,
colWidths=[0.10]*4,
rowColours=row_colors,
colColours=['lightgrey', 'lightgrey',
'lightgrey', 'lightgrey'],
rowLabels=row_labels,
colLabels=col_labels,
loc='lower right')
the_table.auto_set_font_size(False)
the_table.set_fontsize(10)
the_table.scale(1, 1)
for i, val in enumerate(methods):
the_table[i+1,-1].get_text().set_color('white')
# Equality line
eq_line, = axes[row][column].plot(
[0, 1], [0, 1], color='k', linestyle='--', label='Equality Line')
# Set x and y tick markers
axes[row][column].set_xticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=[
'0%', '25%', '50%', '75%', '100%'])
axes[row][column].set_yticks(ticks=[0.0, 0.25, 0.5, 0.75, 1.0], labels=[
'0%', '25%', '50%', '75%', '100%'])
# set x and y limits
axes[row][column].set_xlim(0, 1)
axes[row][column].set_ylim(0, 1)
# set axes title
axes[row][column].set_title('Aggregate', style='italic')
# Individual reliability, cost to access resources Lorenz curve, only plot aggregate
def individual_reliability_aggregate(axes,
prefix,
fpath,
times,
columns=1,
methods=['SVI_scaled'],
svi_weight=None):
"""
Function to plot Lorenz curve of individual reliability for resource accessibility, analyzing the cost to access resources, but only plotting the aggregate results.
cost_atrs:
- this is a list of strings associated with the res_parcels geodataframe attributes that are the variables of interest. They should be the attributes that represent the cost to access each resource.
- each variable is weighted by the PPUNIT Census variable to account for population density differences
methods:
-the x-axis variable the Lorenz curve is plotted against
-acceptable values: 'SVI_scaled', 'Factor 1', and/or 'Factor 2' (refers to attributes of svi geodataframe)
-Currently, Factor 2 is inversed, because it is the economic factor (inversely related to vulnerability)
-TODO: should be a seperate function method to allow input on whether variable is inversed or not
fpath, extension, and times:
- Want to be able to plot time series data of the aggregates, therefore need to read in multiple residential parcel shapefiles with flow decomposition information. 'fpath' is the folder location of the flow decomposition shapefiles. Times, in the format yyyymmddhh, are the times that are read in. The files that are read in take the format {fpath}/{time in times}{extension}
outlier masking:
- Due to the occurance of severe outliers occuring in travel times, (e.g., a residential parcel located at the end of a long roadway that has an extremely high travel time), the cost to access resources are "projected" onto a feasible set. This is done by calculating the interquartile range (IQR). A value is considered an outlier if it is equal to or greater than 3 times the IQR. These values are set to be equal to 3*IQR.
:param axes: axes of figure being manipulated
:type axes: a matplotlib.axes element
:param cost_atrs: the attributes within the res_parcels geodataframe that need to be considered
:type cost_atrs: list of strings
:param svi: the social vulnerabilty dataset to aggregate results to
:type svi: geodataframe
:param fpath: the folder location where the flow decompostiion residential parcels are saved
:type fpath: string
:param extension: the file ending for each low decompostiion residential parcel that will be loaded
:type extension: string
:param times: the times to be loaded, in yyyymmddhh format
:type times: list of stings
:param columns: the number of columns in the time series plots
:type columns: int
:param methods: the x-axis variable
:type methods: list of strings
:param weight: weight to apply to parcels that cannot access the resource. The value will be set to the maximum travel time for that resource times weight
:type weight: int