-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1336 lines (1133 loc) · 54.9 KB
/
utils.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
# -*- coding: utf-8 -*-
""" Utilities for script of paper on
modeling reductions in the environmental footprints embodied in
European Union’s imports through source shifting
Copyright (C) 2018
Bertram F. de Boer
Faculty of Science
Institute of Environmental Sciences (CML)
Department of Industrial Ecology
Einsteinweg 2
2333 CC Leiden
The Netherlands
+31 (0)71 527 1478
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from collections import OrderedDict
import csv
import math
import matplotlib.collections as mpl_col
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import operator
import os
import pandas as pd
import pickle
import cfg
import exiobase as eb
def cm2inch(tup_cm):
""" Convert cm to inch.
Used for figure generation.
Parameters
----------
tup_cm: tuple with values in cm.
Returns
-------
tup_inch: tuple with values in inch.
"""
inch = 2.54
tup_inch = tuple(i/inch for i in tup_cm)
return tup_inch
def get_df_tY_eu28(dict_eb):
""" Get final demand matrix of EU28.
Parameters:
-----------
dict_eb: dictionary with parsed version of EXIOBASE.
Returns:
--------
df_tY_eu28: DataFrame with final demand of EU28.
"""
list_reg_fd = get_list_reg_fd('EU28')
df_tY_eu28 = dict_eb['tY'][list_reg_fd].copy()
for cntr in list_reg_fd:
df_tY_eu28.loc[cntr, cntr] = 0
return df_tY_eu28
def get_dict_df_imp(dict_cf, dict_eb, df_tY):
""" Calculate footprints given final demand
Parameters:
----------
dict_cf: Dictionary with characterization factors for footprints
dict_eb: Dictionary with processed version of EXIOBASE.
df_tY: DataFrame with final demand
Returns:
--------
dict_df_imp: dictionary with DataFrames of footprints
"""
# Diagonalize final demand.
ar_tY = np.diag(df_tY)
df_tYd = pd.DataFrame(ar_tY, index=df_tY.index, columns=df_tY.index)
# Calculate absolute impact of imported products to EU28.
df_cQe = dict_cf['e']
df_cQm = dict_cf['m']
df_cQr = dict_cf['r']
df_cRe = dict_eb['cRe']
df_cRm = dict_eb['cRm']
df_cRr = dict_eb['cRr']
df_cL = dict_eb['cL']
dict_df_imp = {}
dict_df_imp['e'] = df_cQe.dot(df_cRe).dot(df_cL).dot(df_tYd)
dict_df_imp['m'] = df_cQm.dot(df_cRm).dot(df_cL).dot(df_tYd)
dict_df_imp['r'] = df_cQr.dot(df_cRr).dot(df_cL).dot(df_tYd)
return dict_df_imp
def get_dict_imp(dict_df_imp):
""" Convert dictionary with DataFrames of footprints to
dictionary with footprints
Parameters:
----------
dict_df_imp: dictionary with DataFrames of footprints
Returns:
--------
dict_imp: dictionary with footprints
"""
dict_imp = {}
for cat in dict_df_imp:
dict_df = dict_df_imp[cat].T.to_dict()
for imp_cat in dict_df:
dict_imp[imp_cat] = {}
for tup_prod_cntr in dict_df[imp_cat]:
cntr, prod = tup_prod_cntr
if prod not in dict_imp[imp_cat]:
dict_imp[imp_cat][prod] = {}
dict_imp[imp_cat][prod][cntr] = dict_df[imp_cat][tup_prod_cntr]
return dict_imp
def get_dict_imp_cat_unit():
""" Generate dictionary to convert orders of magnitude.
Used for plotting.
Returns:
--------
dict_imp_cat_unit: dictionary linking orders of magnitude for each
footprint.
"""
dict_imp_cat_unit = {}
dict_imp_cat_unit['kg CO2 eq.'] = r'$Pg\/CO_2\/eq.$'
dict_imp_cat_unit['kt'] = r'$Gt$'
dict_imp_cat_unit['Mm3'] = r'$Mm^3$'
dict_imp_cat_unit['km2'] = r'$Gm^2$'
return dict_imp_cat_unit
def get_cf(file_path, df_cQ):
""" Extract characterization factors of footprints from DataFrame
Parameters:
-----------
file_path: string with path to file containing names of footprints
df_cQ: DataFrame with characterization factors
"""
list_imp = []
with open(file_path) as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
for row in csv_file:
list_imp.append(tuple(row))
return df_cQ.loc[list_imp]
def get_dict_cf(dict_eb):
""" Generate dictionary with characterization factors for footprints
Parameters:
dict_eb: dictionary with processed version of EXIOBASE.
Returns:
dict_cf: dictionary with DataFrames of characterization factors.
"""
dict_cf = {}
dict_cf['e'] = get_cf(cfg.data_path+cfg.e_fp_file_name,
dict_eb['cQe'])
dict_cf['m'] = get_cf(cfg.data_path+cfg.m_fp_file_name,
dict_eb['cQm'])
dict_cf['r'] = get_cf(cfg.data_path+cfg.r_fp_file_name,
dict_eb['cQr'])
return dict_cf
def get_dict_eb():
""" Load EXIOBASE.
Returns:
--------
dict_eb: dictionary with processed version of EXIOBASE.
"""
# If EXIOBASE has already been parsed, read the pickle.
if cfg.dict_eb_file_name in os.listdir(cfg.data_path):
dict_eb = pickle.load(open(cfg.data_path+cfg.dict_eb_file_name, 'rb'))
# Else, parse and process EXIOBASE and optionally save for future runs
else:
dict_eb = eb.process(eb.parse())
if cfg.save_eb:
pickle.dump(dict_eb, open(cfg.data_path+cfg.dict_eb_file_name,
'wb'))
return dict_eb
def get_dict_prod_long_short():
""" Generate dictionary linking long and short versions of product names.
Used for plotting.
Returns:
--------
dict_prod_long_short: dictionary linking long and short versions of
product names.
"""
list_prod_long = []
with open(cfg.data_path+cfg.prod_long_file_name) as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
for row in csv_file:
list_prod_long.append(row[0])
list_prod_short = []
with open(cfg.data_path+cfg.prod_short_file_name) as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
for row in csv_file:
list_prod_short.append(row[0])
dict_prod_long_short = {}
for prod_id, prod_long in enumerate(list_prod_long):
prod_long = list_prod_long[prod_id]
prod_short = list_prod_short[prod_id]
dict_prod_long_short[prod_long] = prod_short
return dict_prod_long_short
def get_dict_cntr_short_long():
""" Generate dictionary linking codes and names of countries and regions.
Used for plotting.
Returns:
--------
dict_cntr_short_long: dictionary linking codes and names of
countries and regions.
"""
dict_cntr_short_long = {}
with open(cfg.data_path+cfg.country_code_file_name, 'r') as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
for row in csv_file:
cntr_short = row[0]
cntr_long = row[1]
dict_cntr_short_long[cntr_short] = cntr_long
return dict_cntr_short_long
def get_dict_imp_cat_fp():
""" Generate dictionary linking impact categories and footprint names.
Used for plotting.
Returns:
--------
dict_imp_cat_fp: dictionary linking
impact categories and footprint names.
"""
dict_imp_cat_fp = {}
with open(cfg.data_path+cfg.cf_long_footprint_file_name, 'r') as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
for row in csv_file:
imp_cat = tuple(row[:-1])
fp = row[-1]
dict_imp_cat_fp[imp_cat] = fp
return dict_imp_cat_fp
def get_dict_imp_cat_magnitude():
""" Generate dictionary linking footprints with order of magnitudes.
Used for plotting.
Returns:
--------
dict_imp_cat_magnitude: dictionary linking
footprints with order of magnitudes
"""
dict_imp_cat_magnitude = {}
with open(cfg.data_path+cfg.cf_magnitude_file_name, 'r') as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
for row in csv_file:
imp_cat = tuple(row[:-1])
magnitude = int(row[-1])
dict_imp_cat_magnitude[imp_cat] = magnitude
return dict_imp_cat_magnitude
def get_list_prod_order_cons():
""" Generate concatinated and ordered list of highest contributing products
for each footprint.
Used for plotting.
Returns:
--------
list_prod_order_cons: concatinated and ordered list of
highest contributing products for each footprint.
"""
list_prod_order_cons = []
with open(cfg.data_path+cfg.prod_order_file_name, 'r') as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
for row in csv_file:
list_prod_order_cons.append(row[0])
list_prod_order_cons.reverse()
return list_prod_order_cons
def get_list_reg_fd(reg_fd):
""" Generate list with country codes for all EU28 countries.
Used to select final demand matrix.
Returns:
--------
list_reg_fd: list with country codes for all EU28 countries.
"""
if reg_fd == 'EU28':
with open(cfg.data_path+cfg.eu28_file_name) as read_file:
csv_file = csv.reader(read_file, delimiter='\t')
list_reg_fd = []
for row in csv_file:
list_reg_fd.append(row[0])
else:
list_reg_fd = [reg_fd]
return list_reg_fd
def makedirs(result_dir_name):
""" Make directories for results.
"""
print('\nMaking output directories in:\n\t{}'.format(
cfg.result_dir_path+result_dir_name))
for output_dir_name in cfg.list_output_dir_name:
try:
output_dir_path = (cfg.result_dir_path
+ result_dir_name
+ output_dir_name)
os.makedirs(output_dir_path)
except FileExistsError as e:
print('\n\tOutput directory already exists:\n'
'\t{}\n'
'\tThis run will overwrite previous output.'.format(
output_dir_path))
class Priority:
""" This class is used to calculate highest contributing products to each
footprint.
"""
dict_imp_cat_fp = get_dict_imp_cat_fp()
dict_prod_long_short = get_dict_prod_long_short()
dict_result = OrderedDict()
def __init__(self):
print('\nCreating instance of Priority class.')
makedirs(cfg.priority_setting_dir_name)
def calc(self, dict_cf, dict_eb, df_tY_eu28):
""" Calculate highest contributing products to each footprint.
Parameters
----------
dict_cf: dictionary with characterisation factors of footprints
dict_eb: dictionary with processed version of EXIOBASE
df_tY_eu28: DataFrame with EU28 imported final demand
"""
print('\nCalculating highest contributing products to each footprint.')
# Sum over all EU28 countries and imported final demand categories.
df_tY_eu28_fdsum = df_tY_eu28.sum(axis=1)
# Calculate EU28 import embodied footprints.
dict_df_imp = get_dict_df_imp(dict_cf, dict_eb, df_tY_eu28_fdsum)
# Select and order highest contributing products up to configured limit
for cat in dict_df_imp:
df_imp_prod = dict_df_imp[cat].sum(axis=1, level=1)
dict_imp_prod = df_imp_prod.T.to_dict()
dict_imp_prod_sum = dict_df_imp[cat].sum(axis=1).to_dict()
for imp_cat in dict_imp_prod:
self.dict_result[imp_cat] = OrderedDict()
list_imp_sort = sorted(dict_imp_prod[imp_cat].items(),
key=operator.itemgetter(1),
reverse=True)
imp_cum = 0
bool_add = True
for tup_prod_abs_id, tup_prod_abs in enumerate(list_imp_sort):
(prod, imp_abs) = tup_prod_abs
imp_rel = imp_abs/dict_imp_prod_sum[imp_cat]
imp_cum = imp_cum + imp_rel
if imp_cum < cfg.imp_cum_lim_priority:
self.dict_result[imp_cat][prod] = imp_abs
elif bool_add:
self.dict_result[imp_cat][prod] = imp_abs
bool_add = False
def log(self):
""" Write highest contributing products for each footprint to file
"""
priority_setting_dir_path = (cfg.result_dir_path
+ cfg.priority_setting_dir_name)
log_file_name = 'log.txt'
log_file_path = (priority_setting_dir_path
+ cfg.txt_dir_name
+ log_file_name)
print('\nSaving priority setting log to:\n\t{}'.format(
priority_setting_dir_path+cfg.txt_dir_name))
with open(log_file_path, 'w') as write_file:
csv_file = csv.writer(write_file,
delimiter='\t',
lineterminator='\n')
csv_file.writerow(['Footprint', 'Product'])
for imp_cat in self.dict_result:
csv_file.writerow([])
fp = self.dict_imp_cat_fp[imp_cat]
for prod in self.dict_result[imp_cat]:
csv_file.writerow([fp, prod])
def plot(self):
""" Plot highest contributing products of each footprint.
"""
dict_imp_cat_magnitude = get_dict_imp_cat_magnitude()
analysis_name = 'priority_setting'
priority_setting_dir_path = (cfg.result_dir_path
+ cfg.priority_setting_dir_name)
pdf_dir_path = priority_setting_dir_path+cfg.pdf_dir_name
png_dir_path = priority_setting_dir_path+cfg.png_dir_name
print('\nSaving priority setting plots to:\n\t{}\n\t{}'.format(
pdf_dir_path,
png_dir_path))
plt.close('all')
dict_imp_cat_unit = get_dict_imp_cat_unit()
fig = plt.figure(figsize=cm2inch((16, cfg.font_size)), dpi=cfg.dpi)
for imp_cat_id, imp_cat in enumerate(self.dict_result):
plot_id = imp_cat_id+1
plot_loc = 220+plot_id
ax = fig.add_subplot(plot_loc)
fp = self.dict_imp_cat_fp[imp_cat]
unit = dict_imp_cat_unit[imp_cat[-1]]
ax.set_xlabel('{} [{}]'.format(fp, unit))
df = pd.DataFrame(self.dict_result[imp_cat],
index=['import'])
df.rename(columns=self.dict_prod_long_short, inplace=True)
df_column_order = list(df.columns)
df_column_order.reverse()
df = df.reindex(df_column_order, axis=1)
column_name_dummy = ''
prod_order_dummy = df_column_order
while len(df.T) < 9:
df[column_name_dummy] = 0
prod_order_dummy.reverse()
prod_order_dummy.append(column_name_dummy)
prod_order_dummy.reverse()
df = df.reindex(df_column_order, axis=1)
column_name_dummy += ' '
df.T.plot.barh(stacked=True,
ax=ax,
legend=False,
color='C0',
width=0.8)
yticklabels = ax.get_yticklabels()
ax.set_yticklabels(yticklabels)
plt.locator_params(axis='x', nbins=1)
ax.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
xlim = ax.get_xlim()
xlim_max_magn = 10**np.floor(np.log10(xlim[1]))
xlim_max_ceil = math.ceil(xlim[1]/xlim_max_magn)*xlim_max_magn
tup_xlim_max_ceil = (int(xlim[0]), xlim_max_ceil)
ax.set_xlim(tup_xlim_max_ceil)
xtick_magnitude = dict_imp_cat_magnitude[imp_cat]
list_xtick = [i/xtick_magnitude for i in tup_xlim_max_ceil]
list_xtick[0] = int(list_xtick[0])
ax.set_xticks(list(tup_xlim_max_ceil))
ax.set_xticklabels(list_xtick)
xtick_objects = ax.xaxis.get_major_ticks()
xtick_objects[0].label1.set_horizontalalignment('left')
xtick_objects[-1].label1.set_horizontalalignment('right')
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
ax.yaxis.set_tick_params(size=0)
fig.tight_layout()
plt.subplots_adjust(wspace=1)
fig_file_name = analysis_name+'.pdf'
fig_file_path = pdf_dir_path+fig_file_name
fig.savefig(fig_file_path)
fig_file_name = analysis_name+'.png'
fig_file_path = png_dir_path+fig_file_name
fig.savefig(fig_file_path)
class SourceShift():
""" This class is used to calculate reductions in
import embedded footprints by source shifting.
"""
dict_imp_cat_fp = get_dict_imp_cat_fp()
dict_imp_cat_magnitude = get_dict_imp_cat_magnitude()
dict_prod_long_short = get_dict_prod_long_short()
dict_shift_result = {}
dict_reduc_result = {}
def __init__(self):
print('\nCreating instance of SourceShift class.')
makedirs(cfg.shift_dir_name)
makedirs(cfg.reduc_dir_name)
def calc_shift(self, dict_cf, dict_eb, df_tY_eu28):
""" Optimize sourcing for each footprint.
Parameters
----------
dict_cf: dictionary with characterisation factors of footprints
dict_eb: dictionary with processed version of EXIOBASE
df_tY_eu28: DataFrame with EU28 imported final demand
"""
print('\nReducing import embodied footprints of EU28 by '
'source shifting.')
# Calculate import embodied footprints.
df_tY_eu28_fdsum = df_tY_eu28.sum(axis=1)
dict_df_imp = get_dict_df_imp(dict_cf, dict_eb, df_tY_eu28_fdsum)
dict_imp = get_dict_imp(dict_df_imp)
# Calculate footprint intensities per M Euro
dict_df_imp_pME = {}
dict_df_imp_pME['e'] = dict_cf['e'].dot(dict_eb['cRe']).dot(
dict_eb['cL'])
dict_df_imp_pME['m'] = dict_cf['m'].dot(dict_eb['cRm']).dot(
dict_eb['cL'])
dict_df_imp_pME['r'] = dict_cf['r'].dot(dict_eb['cRr']).dot(
dict_eb['cL'])
dict_imp_pME = get_dict_imp(dict_df_imp_pME)
# For each footprint, for each product, sort countries according to
# footprint intensity.
dict_imp_prod_cntr_sort = {}
for imp_cat in dict_imp:
dict_imp_prod_cntr_sort[imp_cat] = OrderedDict()
for prod in dict_imp[imp_cat]:
dict_imp_prod_cntr_sort[imp_cat][prod] = OrderedDict()
list_imp_pME_prod_cntr_sort = sorted(
dict_imp_pME[imp_cat][prod].items(),
key=operator.itemgetter(1))
for tup_cntr_imp_pME in list_imp_pME_prod_cntr_sort:
cntr, imp_pME_prod_cntr = tup_cntr_imp_pME
dict_imp_prod_cntr_sort[imp_cat][prod][cntr] = (
dict_imp[imp_cat][prod][cntr])
# For all products, for all countries,
# calculate how much is imported by EU28.
df_tY_eu28_cntr = df_tY_eu28.sum(axis=1, level=0)
dict_tY_eu28_cntr = df_tY_eu28_cntr.to_dict()
dict_tY_eu28_cntr_import = {}
for cntr_fd in dict_tY_eu28_cntr:
for tup_cntr_prod in dict_tY_eu28_cntr[cntr_fd]:
cntr, prod = tup_cntr_prod
if prod not in dict_tY_eu28_cntr_import:
dict_tY_eu28_cntr_import[prod] = {}
if cntr not in dict_tY_eu28_cntr_import[prod]:
dict_tY_eu28_cntr_import[prod][cntr] = 0
if cntr_fd is not cntr:
dict_tY_eu28_cntr_import[prod][cntr] += (
dict_tY_eu28_cntr[cntr_fd][tup_cntr_prod])
# For all products, for all countries,
# calculate how much is exported in total.
df_tY_world = dict_eb['tY'].copy()
list_cntr = list(df_tY_world.columns.get_level_values(0))
for cntr in list_cntr:
df_tY_world.loc[cntr, cntr] = 0
df_tY_world_ex = df_tY_world.sum(axis=1)
dict_tY_world_ex = df_tY_world_ex.to_dict()
dict_tY_world_ex_prod_cntr = {}
for tup_cntr_prod in dict_tY_world_ex:
cntr, prod = tup_cntr_prod
if prod not in dict_tY_world_ex_prod_cntr:
dict_tY_world_ex_prod_cntr[prod] = {}
dict_tY_world_ex_prod_cntr[prod][cntr] = (
dict_tY_world_ex[tup_cntr_prod])
# Initialize dictionary with results.
for imp_cat in dict_imp_prod_cntr_sort:
self.dict_shift_result[imp_cat] = {}
for prod in dict_imp_prod_cntr_sort[imp_cat]:
self.dict_shift_result[imp_cat][prod] = {}
for cntr in dict_imp_prod_cntr_sort[imp_cat][prod]:
imp_pME_prod_cntr = dict_imp_pME[imp_cat][prod][cntr]
y_prod_cntr = dict_tY_eu28_cntr_import[prod][cntr]
x_prod_cntr = dict_tY_world_ex_prod_cntr[prod][cntr]
if x_prod_cntr >= cfg.x_prod_cntr_min:
self.dict_shift_result[imp_cat][prod][cntr] = {}
self.dict_shift_result[imp_cat][prod][cntr]['imp_pME'] = (
imp_pME_prod_cntr)
self.dict_shift_result[imp_cat][prod][cntr]['export'] = (
x_prod_cntr)
self.dict_shift_result[imp_cat][prod][cntr]['EU_import_old'] = (
y_prod_cntr)
self.dict_shift_result[imp_cat][prod][cntr]['EU_import_new'] = (
0)
# For each product, calculate total EU28 imports.
dict_tY_prod = {}
for prod in dict_tY_eu28_cntr_import:
dict_tY_prod[prod] = 0
for cntr in dict_tY_eu28_cntr_import[prod]:
x_prod_cntr = dict_tY_world_ex_prod_cntr[prod][cntr]
if x_prod_cntr >= cfg.x_prod_cntr_min:
dict_tY_prod[prod] += dict_tY_eu28_cntr_import[prod][cntr]
# For each footprint, for each product, for each exporting country
# Shift imports from EU28 to countries with lowest impact intensity
# Up to current level of country export
for imp_cat in dict_imp_prod_cntr_sort:
for prod in dict_imp_prod_cntr_sort[imp_cat]:
y_prod = dict_tY_prod[prod]
for cntr in dict_imp_prod_cntr_sort[imp_cat][prod]:
x_prod_cntr = dict_tY_world_ex_prod_cntr[prod][cntr]
# Exclude countries with very low exports, due to noise.
if x_prod_cntr >= cfg.x_prod_cntr_min:
# If export of country is smaller than remaining
# EU28 import, redirect all exports to EU 28
if x_prod_cntr < y_prod:
self.dict_shift_result[imp_cat][prod][cntr]['EU_import_new'] = (
x_prod_cntr)
y_prod -= x_prod_cntr
# Else, redirect exports to EU28 up to remaining level
# of import.
elif y_prod > 0:
self.dict_shift_result[imp_cat][prod][cntr]['EU_import_new'] = (
y_prod)
y_prod -= y_prod
def calc_reduc(self, dict_cf, dict_eb, df_tY_eu28):
""" Calculate footprints for new EU28 imported final demand.
Parameters
----------
dict_cf: dictionary with characterisation factors of footprints
dict_eb: dictionary with processed version of EXIOBASE
df_tY_eu28: DataFrame with EU28 imported final demand
"""
print('\nCalculating import embodied footprint reductions.')
# Restructure new EU28 import data for DataFrames.
dict_df_tY_import_new = {}
for imp_cat_id, imp_cat in enumerate(self.dict_shift_result):
dict_df_tY_import_new[imp_cat] = {}
for prod in self.dict_shift_result[imp_cat]:
for cntr in self.dict_shift_result[imp_cat][prod]:
dict_df_tY_import_new[imp_cat][(cntr, prod)] = (
self.dict_shift_result[imp_cat][prod][cntr]['EU_import_new'])
# Calculate footprints for new EU28 imported final demand.
dict_imp_new_reg = {}
for imp_cat_id, imp_cat_sel in enumerate(dict_df_tY_import_new):
df_tY_eu28_fdsum = df_tY_eu28.sum(axis=1)
df_tY_eu28_import = df_tY_eu28_fdsum.copy()
df_tY_eu28_import[:] = 0
df_tY_eu28_import[list(
dict_df_tY_import_new[imp_cat_sel].keys())] = (
list(dict_df_tY_import_new[imp_cat_sel].values()))
df_tY_eu28_import.columns = ['import']
dict_df_imp_new = get_dict_df_imp(
dict_cf, dict_eb, df_tY_eu28_import)
dict_imp_new = get_dict_imp(dict_df_imp_new)
dict_imp_new_reg[imp_cat_sel] = {}
for imp_cat_eff in dict_imp_new:
if imp_cat_eff not in dict_imp_new_reg[imp_cat_sel]:
dict_imp_new_reg[imp_cat_sel][imp_cat_eff] = {}
for prod in dict_imp_new[imp_cat_eff]:
if prod not in dict_imp_new_reg[imp_cat_sel][imp_cat_eff]:
dict_imp_new_reg[imp_cat_sel][imp_cat_eff][prod] = 0
for cntr in dict_imp_new[imp_cat_eff][prod]:
dict_imp_new_reg[imp_cat_sel][imp_cat_eff][prod] += (
dict_imp_new[imp_cat_eff][prod][cntr])
# Calculate footprints for old EU28 imported final demand.
dict_imp_cat_old = {}
for imp_cat in self.dict_shift_result:
dict_imp_cat_old[imp_cat] = {}
for prod in self.dict_shift_result[imp_cat]:
dict_imp_cat_old[imp_cat][prod] = 0
for cntr in self.dict_shift_result[imp_cat][prod]:
imp_pME = self.dict_shift_result[imp_cat][prod][cntr]['imp_pME']
y_old = self.dict_shift_result[imp_cat][prod][cntr]['EU_import_old']
imp_abs = imp_pME*y_old
dict_imp_cat_old[imp_cat][prod] += imp_abs
# Put footprints of new and old EU28 imported final demand in
# dictionary.
for imp_cat_sel_id, imp_cat_sel in enumerate(dict_imp_new_reg):
self.dict_reduc_result[imp_cat_sel] = {}
for imp_cat_eff_id, imp_cat_eff in (
enumerate(dict_imp_new_reg[imp_cat_sel])):
self.dict_reduc_result[imp_cat_sel][imp_cat_eff] = {}
self.dict_reduc_result[imp_cat_sel][imp_cat_eff]['Ante'] = (
dict_imp_cat_old[imp_cat_eff])
self.dict_reduc_result[imp_cat_sel][imp_cat_eff]['Post'] = (
dict_imp_new_reg[imp_cat_sel][imp_cat_eff])
def calc(self, dict_cf, dict_eb, df_tY_eu28):
""" Calculate reduction in import embodied footprints of EU28
by source shifting
Parameters
----------
dict_cf: dictionary with characterisation factors of footprints
dict_eb: dictionary with processed version of EXIOBASE
df_tY_eu28: DataFrame with EU28 imported final demand
"""
self.calc_shift(dict_cf, dict_eb, df_tY_eu28)
self.calc_reduc(dict_cf, dict_eb, df_tY_eu28)
def test(self):
shift_dir_path = cfg.result_dir_path+cfg.shift_dir_name
test_dir_path = shift_dir_path+cfg.test_dir_name
test_export_file_name = 'test_export.txt'
test_export_file_path = test_dir_path+test_export_file_name
test_import_sum_file_name = 'test_import_sum.txt'
test_import_sum_file_path = test_dir_path+test_import_sum_file_name
error_export_bool = False
error_import_sum_bool = False
with open(test_export_file_path, 'w') as write_file:
csv_export_file = csv.writer(write_file,
delimiter='\t',
lineterminator='\n')
with open(test_import_sum_file_path, 'w') as write_file:
csv_import_sum_file = csv.writer(write_file,
delimiter='\t',
lineterminator='\n')
for imp_cat in self.dict_shift_result:
fp = self.dict_imp_cat_fp[imp_cat]
for prod in self.dict_shift_result[imp_cat]:
EU_import_old_sum = 0
EU_import_new_sum = 0
for cntr in self.dict_shift_result[imp_cat][prod]:
export = self.dict_shift_result[imp_cat][prod][cntr]['export']
EU_import_old = self.dict_shift_result[imp_cat][prod][cntr]['EU_import_old']
EU_import_new = self.dict_shift_result[imp_cat][prod][cntr]['EU_import_new']
EU_import_old_sum += EU_import_old
EU_import_new_sum += EU_import_new
if EU_import_new > export:
if not error_export_bool:
csv_export_file.writerow(['New EU import larger than export sourcing country:'])
csv_export_file.writerow(['Footprint',
'Product',
'Exporting country',
'Export',
'Old EU import',
'New EU import'])
error_export_bool = True
csv_export_file.writerow([fp,
prod,
cntr,
export,
EU_import_old,
EU_import_new])
if not(math.isclose(EU_import_old_sum, EU_import_new_sum)):
if not error_import_sum_bool:
csv_import_sum_file.writerow(['Sums of old and new EU import do not match:'])
csv_import_sum_file.writerow(['Footprint',
'Product',
'Exporting country',
'Export',
'Sum old EU import',
'Sum new EU import'])
error_import_sum_bool = True
csv_import_sum_file.writerow([fp,
prod,
cntr,
export,
EU_import_old_sum,
EU_import_new_sum])
if not error_export_bool:
csv_export_file.writerow(['Success! New EU import never larger than export.'])
if not error_import_sum_bool:
csv_import_sum_file.writerow(['Success! Sums of old and new EU import always match.'])
def plot_shift(self):
""" Plot source shifts of imports
"""
dict_cntr_short_long = get_dict_cntr_short_long()
shift_dir_path = cfg.result_dir_path+cfg.shift_dir_name
pdf_dir_path = shift_dir_path+cfg.pdf_dir_name
png_dir_path = shift_dir_path+cfg.png_dir_name
print('\nSaving source shift plots to:\n\t{}\n\t{}'.format(
png_dir_path,
pdf_dir_path))
# For both before and after source shifting, For each footprint,
# for each product get list of labels from highest contributing
# exporting country
list_eu_import = ('EU_import_old', 'EU_import_new')
dict_cntr_label = {}
for eu_import in list_eu_import:
dict_cntr_label[eu_import] = {}
for imp_cat in self.dict_shift_result:
dict_cntr_label[eu_import][imp_cat] = {}
for prod in self.dict_shift_result[imp_cat]:
imp_abs_sum = 0
dict_cntr = {}
for cntr in self.dict_shift_result[imp_cat][prod]:
imp_pME = self.dict_shift_result[imp_cat][prod][cntr]['imp_pME']
y_new = self.dict_shift_result[imp_cat][prod][cntr][eu_import]
imp_abs = imp_pME*y_new
imp_abs_sum += imp_abs
dict_cntr[cntr] = imp_abs
list_imp_cat_prod_sort = sorted(
dict_cntr.items(),
key=operator.itemgetter(1), reverse=True)
list_imp_cat_prod_sort_trunc = []
if imp_abs_sum > 0:
imp_cum = 0
bool_add = True
for tup_cntr_imp in list_imp_cat_prod_sort:
cntr, imp_abs = tup_cntr_imp
imp_rel = imp_abs/imp_abs_sum
imp_cum += imp_rel
if imp_cum <= cfg.imp_cum_lim_source_shift:
list_imp_cat_prod_sort_trunc.append(cntr)
elif bool_add:
list_imp_cat_prod_sort_trunc.append(cntr)
bool_add = False
dict_cntr_label[eu_import][imp_cat][prod] = (
list_imp_cat_prod_sort_trunc)
# Plot exports and current levels of EU28 imported final demand
dict_lim = {}
dict_ax = {}
eu_import = 'EU_import_old'
for imp_cat in self.dict_shift_result:
dict_lim[imp_cat] = {}
dict_ax[imp_cat] = {}
for prod in self.dict_shift_result[imp_cat]:
plt.close('all')
x_start = 0
y_start = 0
list_rect_y = []
list_rect_x = []
fig = plt.figure(figsize=cm2inch((16, 8)), dpi=cfg.dpi)
ax = plt.gca()
for cntr in self.dict_shift_result[imp_cat][prod]:
imp_pME_prod_cntr = self.dict_shift_result[imp_cat][prod][cntr]['imp_pME']
y_prod_cntr = self.dict_shift_result[imp_cat][prod][cntr][eu_import]
x_prod_cntr = self.dict_shift_result[imp_cat][prod][cntr]['export']
if cntr in (dict_cntr_label[eu_import][imp_cat][prod]):
cntr_long = dict_cntr_short_long[cntr]
plt.text(x_start+y_prod_cntr/2,
y_start+imp_pME_prod_cntr,
' '+cntr_long,
rotation=90,
verticalalignment='bottom',
horizontalalignment='center',
color='C0')
rect_y = patches.Rectangle((x_start, y_start),
y_prod_cntr,
imp_pME_prod_cntr)
rect_x = patches.Rectangle((x_start, y_start),
x_prod_cntr,
imp_pME_prod_cntr)
list_rect_y.append(rect_y)
list_rect_x.append(rect_x)
x_max = x_start+x_prod_cntr
y_max = y_start+imp_pME_prod_cntr
x_start += x_prod_cntr
col_rect_y = mpl_col.PatchCollection(list_rect_y,
facecolor='C0')
col_rect_x = mpl_col.PatchCollection(list_rect_x,
facecolor='gray')
ax.add_collection(col_rect_x)
ax.add_collection(col_rect_y)
ax.autoscale()
dict_lim[imp_cat][prod] = {}
dict_lim[imp_cat][prod]['x'] = (0, x_max)
dict_lim[imp_cat][prod]['y'] = (0, y_max)
dict_ax[imp_cat][prod] = ax
# Plot new EU28 imported final demand
eu_import = 'EU_import_new'
for imp_cat in self.dict_shift_result:
for prod in self.dict_shift_result[imp_cat]:
plt.close('all')
x_start = 0
y_start = 0
list_rect_y = []
ax = dict_ax[imp_cat][prod]
for cntr in self.dict_shift_result[imp_cat][prod]:
imp_pME_prod_cntr = self.dict_shift_result[imp_cat][prod][cntr]['imp_pME']
y_prod_cntr_new = self.dict_shift_result[imp_cat][prod][cntr][eu_import]
x_prod_cntr = self.dict_shift_result[imp_cat][prod][cntr]['export']
rect_y = patches.Rectangle((x_start, y_start),
y_prod_cntr_new,
imp_pME_prod_cntr)
if cntr in dict_cntr_label[eu_import][imp_cat][prod]:
cntr_long = dict_cntr_short_long[cntr]
x_text = x_start+x_prod_cntr/2
y_text = y_start+imp_pME_prod_cntr
ax.text(x_text,
y_text,
' '+cntr_long,
rotation=90,
verticalalignment='bottom',
horizontalalignment='center',
color='green')
list_rect_y.append(rect_y)
x_start += x_prod_cntr
rect_y = patches.Rectangle((0, 0), 0, 0)
list_rect_y.append(rect_y)
col_rect_y = mpl_col.PatchCollection(list_rect_y,
facecolor='green')
col_rect_y.set_alpha(0.5)
ax.add_collection(col_rect_y)
ax.autoscale()
fig = ax.get_figure()
unit = imp_cat[-1]
ax.set_ylabel('{}/M€'.format(unit))
ax.set_xlabel('M€')
ax.set_xlim(dict_lim[imp_cat][prod]['x'])
ax.set_ylim(dict_lim[imp_cat][prod]['y'])
ax.locator_params(axis='both', nbins=4, tight=True)
ax.ticklabel_format(style='sci', axis='both', scilimits=(0, 0))
prod_short = self.dict_prod_long_short[prod]
prod_short_lower = prod_short.lower()
prod_short_lower_strip = prod_short_lower.strip()
prod_short_lower_strip = prod_short_lower_strip.replace(':', '')