-
Notifications
You must be signed in to change notification settings - Fork 6
/
openIO.py
4051 lines (3494 loc) · 240 KB
/
openIO.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
"""
Class that creates symmetric Input-Output tables based on the Supply and Use economic tables provided by Statistic
Canada, available here: https://www150.statcan.gc.ca/n1/en/catalogue/15-602-X
Multiple transformation models are available (industry technology assumption, fixed industry sales structure, etc.) and
the type of classification (productxproduct, or industryxindustry) can be selected as well.
Also produces environmental extensions for the symmetric tables generated based on data from the NPRI found here:
https://open.canada.ca/data/en/dataset/1fb7d8d4-7713-4ec6-b957-4a882a84fed3
"""
import pandas as pd
import numpy as np
import re
import pkg_resources
import os
import pymrio
import json
import country_converter as coco
import logging
import warnings
import gzip
import pickle
import math
class IOTables:
def __init__(self, folder_path, exiobase_folder, endogenizing_capitals=False):
"""
:param folder_path: [string] the path to the folder with the economic data (e.g. /../Detail level/)
:param exiobase_folder: [string] path to exiobase folder for international imports (optional)
:param endogenizing_capitals: [boolean] True if you want to endogenize capitals
:param aggregated_ghgs: [boolean] True to work with aggregated GHG physical flow accounts. False requires you to
have access to the disaggregated files provided by StatCan.
"""
# ignoring some warnings
warnings.filterwarnings(action='ignore', category=FutureWarning)
warnings.filterwarnings(action='ignore', category=np.VisibleDeprecationWarning)
warnings.filterwarnings(action='ignore', category=pd.errors.PerformanceWarning)
# set up logging tool
logger = logging.getLogger('openIO-Canada')
logger.setLevel(logging.INFO)
logger.handlers = []
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.propagate = False
# set up logging tool for country_converter
coco_logger = coco.logging.getLogger()
coco_logger.setLevel(logging.CRITICAL)
logger.info('Reading all the Excel files...')
self.level_of_detail = [i for i in os.path.normpath(folder_path).split(os.sep) if 'level' in i][-1]
self.exiobase_folder = exiobase_folder
self.endogenizing = endogenizing_capitals
# values
self.V = pd.DataFrame()
self.U = pd.DataFrame()
self.A = pd.DataFrame()
self.K = pd.DataFrame()
self.Z = pd.DataFrame()
self.W = pd.DataFrame()
self.R = pd.DataFrame()
self.Y = pd.DataFrame()
self.WY = pd.DataFrame()
self.g = pd.DataFrame()
self.inv_g = pd.DataFrame()
self.q = pd.DataFrame()
self.inv_q = pd.DataFrame()
self.F = pd.DataFrame()
self.S = pd.DataFrame()
self.FY = pd.DataFrame()
self.C = pd.DataFrame()
self.INT_imports = pd.DataFrame()
self.L = pd.DataFrame()
self.E = pd.DataFrame()
self.D = pd.DataFrame()
self.who_uses_int_imports_U = pd.DataFrame()
self.who_uses_int_imports_K = pd.DataFrame()
self.who_uses_int_imports_Y = pd.DataFrame()
self.A_exio = pd.DataFrame()
self.Z_exio = pd.DataFrame()
self.x_exio = pd.DataFrame()
self.K_exio = pd.DataFrame()
self.S_exio = pd.DataFrame()
self.F_exio = pd.DataFrame()
self.C_exio = pd.DataFrame()
self.link_openio_exio_A = pd.DataFrame()
self.link_openio_exio_K = pd.DataFrame()
self.link_openio_exio_Y = pd.DataFrame()
self.merchandise_imports = pd.DataFrame()
self.merchandise_imports_scaled_U = pd.DataFrame()
self.merchandise_imports_scaled_K = pd.DataFrame()
self.merchandise_imports_scaled_Y = pd.DataFrame()
self.minerals = pd.DataFrame()
# metadata
self.emission_metadata = pd.DataFrame()
self.unit_exio = pd.DataFrame()
self.methods_metadata = pd.DataFrame()
self.industries = []
self.commodities = []
self.factors_of_production = []
self.matching_dict = {'AB': 'Alberta',
'BC': 'British Columbia',
'CE': 'Canadian territorial enclaves abroad',
'MB': 'Manitoba',
'NB': 'New Brunswick',
'NL': 'Newfoundland and Labrador',
'NS': 'Nova Scotia',
'NT': 'Northwest Territories',
'NU': 'Nunavut',
'ON': 'Ontario',
'PE': 'Prince Edward Island',
'QC': 'Quebec',
'SK': 'Saskatchewan',
'YT': 'Yukon'}
files = [i for i in os.walk(folder_path)]
files = [i for i in files[0][2] if i[:2] in self.matching_dict.keys() and 'SUT' in i]
files.sort()
self.year = int(files[0].split('SUT_C')[1].split('_')[0])
if self.year in [2018, 2019, 2020]:
self.aggregated_ghgs = False
else:
self.aggregated_ghgs = True
try:
self.NPRI = pd.read_excel(pkg_resources.resource_stream(
__name__, '/Data/Environmental_data/NPRI-INRP_DataDonnées_' + str(self.year) + '.xlsx'), None)
self.NPRI_file_year = self.year
# 2018 by default (for older years)
except FileNotFoundError:
self.NPRI = pd.read_excel(pkg_resources.resource_stream(
__name__, '/Data/Environmental_data/NPRI-INRP_DataDonnées_2018.xlsx'), None)
self.NPRI_file_year = 2018
logger.info("Formatting the Supply and Use tables...")
for province_data in files:
supply = pd.read_excel(os.path.join(folder_path, province_data), 'Supply')
use = pd.read_excel(os.path.join(folder_path, province_data), 'Use_Basic')
region = province_data[:2]
self.format_tables(supply, use, region)
self.W = self.W.fillna(0)
self.WY = self.WY.fillna(0)
self.Y = self.Y.fillna(0)
self.q = self.q.fillna(0)
self.g = self.g.fillna(0)
self.U = self.U.fillna(0)
self.V = self.V.fillna(0)
# output of the industries (g) should match between V and U+W
assert np.isclose((self.U.sum()+self.W.sum()).sum(), self.g.sum().sum())
# output of the commodities (q) should match between V and U+Y adjusted for international imports
assert np.isclose((self.U.sum(1) + self.Y.sum(1) - self.INT_imports.sum(1)).sum(), self.q.sum(1).sum())
logger.info("Modifying names of duplicated sectors...")
self.dealing_with_duplicated_names()
logger.info('Organizing final demand sectors...')
self.organize_final_demand()
logger.info('Removing IOIC codes from index...')
self.remove_codes()
if self.endogenizing:
logger.info('Endogenizing capitals of OpenIO-Canada...')
self.endogenizing_capitals()
logger.info("Balancing inter-provincial trade...")
self.province_import_export(
pd.read_excel(
os.path.join(folder_path, [i for i in [j for j in os.walk(folder_path)][0][2] if 'Provincial_trade_flow' in i][0]),
'Data'))
if self.exiobase_folder:
logger.info('Pre-treatment of international trade data...')
self.determine_sectors_importing()
self.load_merchandise_international_trade_database()
logger.info("Linking international trade data to openIO-Canada...")
self.link_merchandise_database_to_openio()
logger.info("Building the symmetric tables...")
self.gimme_symmetric_iot()
if self.exiobase_folder:
logger.info("Linking openIO-Canada to Exiobase...")
self.link_international_trade_data_to_exiobase()
self.remove_abroad_enclaves()
if self.exiobase_folder:
self.concatenate_matrices()
logger.info("Extracting and formatting environmental data from the NPRI file...")
self.extract_environmental_data()
logger.info("Matching emission data from NPRI to IOT sectors...")
self.match_npri_data_to_iots()
logger.info("Matching GHG accounts to IOT sectors...")
if self.aggregated_ghgs:
self.match_aggregated_ghg_accounts_to_iots()
else:
self.match_disaggregated_ghg_accounts_to_iots()
logger.info("Matching water accounts to IOT sectors...")
self.match_water_accounts_to_iots()
logger.info("Matching energy accounts to IOT sectors...")
self.match_energy_accounts_to_iots()
logger.info("Matching mineral extraction data to IOT sectors...")
self.match_mineral_extraction_to_iots()
logger.info("Creating the characterization matrix...")
self.characterization_matrix()
logger.info("Refining the GHG emissions for the agriculture sector...")
self.better_distribution_for_agriculture_ghgs()
logger.info("Cleaning province and country names...")
self.differentiate_country_names_openio_exio()
logger.info("Refining the GHG emissions for the meat sector...")
self.refine_meat_sector()
self.convert_F_to_commodity()
logger.info("Adding HFP and PFC flows...")
self.add_hfc_emissions()
logger.info("Refining water consumption of livestock and crops...")
self.add_water_consumption_flows_for_livestock_and_crops()
logger.info("Adding plastic waste flows...")
self.add_plastic_emissions()
logger.info("Normalizing emissions...")
self.normalize_flows()
logger.info("Differentiating biogenic from fossil CO2 emissions...")
self.differentiate_biogenic_carbon_emissions()
logger.info("Done extracting openIO-Canada!")
def format_tables(self, supply, use, region):
"""
Extracts the relevant dataframes from the Excel files in the Stat Can folder
:param supply: the supply table
:param use: the use table
:param region: the province of Canada to compile data for
:return: self.W, self.WY, self.Y, self.g, self.q, self.V, self.U
"""
supply_table = supply
use_table = use
if self.year in [2014, 2015, 2016, 2017]:
# starting_line is the line in which the Supply table starts (the first green row)
starting_line = 11
# starting_line_values is the line in which the first value appears
starting_line_values = 16
elif self.year in [2018, 2019, 2020]:
# starting_line is the line in which the Supply table starts (the first green row)
starting_line = 3
# starting_line_values is the line in which the first value appears
starting_line_values = 7
if not self.industries:
for i in range(0, len(supply_table.columns)):
if supply_table.iloc[starting_line, i] == 'Total':
break
if supply_table.iloc[starting_line, i] not in [np.nan, 'Industries']:
# tuple with code + name (need code to deal with duplicate names in detailed levels)
self.industries.append((supply_table.iloc[starting_line+1, i],
supply_table.iloc[starting_line, i]))
# remove fictive sectors
self.industries = [i for i in self.industries if not re.search(r'^F', i[0])]
if not self.commodities:
for i, element in enumerate(supply_table.iloc[:, 0].tolist()):
if type(element) == str:
# identify by their codes
if re.search(r'^[M,F,N,G,I,E]\w*\d', element):
self.commodities.append((element, supply_table.iloc[i, 1]))
elif re.search(r'^P\w*\d', element) or re.search(r'^GVA', element):
self.factors_of_production.append((element, supply_table.iloc[i, 1]))
final_demand = []
for i in range(0, len(use_table.columns)):
if use_table.iloc[starting_line, i] in self.matching_dict.values():
break
if use_table.iloc[starting_line, i] not in [np.nan, 'Industries']:
final_demand.append((use_table.iloc[starting_line+1, i],
use_table.iloc[starting_line, i]))
final_demand = [i for i in final_demand if i not in self.industries and i[1] != 'Total']
df = supply_table.iloc[starting_line_values-2:, 2:]
df.index = list(zip(supply_table.iloc[starting_line_values-2:, 0].tolist(),
supply_table.iloc[starting_line_values-2:, 1].tolist()))
df.columns = list(zip(supply_table.iloc[starting_line+1, 2:].tolist(),
supply_table.iloc[starting_line, 2:].tolist()))
supply_table = df
df = use_table.iloc[starting_line_values-2:, 2:]
df.index = list(zip(use_table.iloc[starting_line_values-2:, 0].tolist(),
use_table.iloc[starting_line_values-2:, 1].tolist()))
df.columns = list(zip(use_table.iloc[starting_line+1, 2:].tolist(),
use_table.iloc[starting_line, 2:].tolist()))
use_table = df
# fill with zeros
supply_table = supply_table.astype(str).replace(to_replace=['.'], value='0').astype(float)
use_table = use_table.astype(str).replace(to_replace=['.'], value='0').astype(float)
if self.level_of_detail == 'Detail level':
# tables from k$ to $
supply_table *= 1000
use_table *= 1000
else:
# tables from M$ to $
supply_table *= 1000000
use_table *= 1000000
# check calculated totals matched displayed totals
assert np.allclose(use_table.iloc[:, use_table.columns.get_loc(('TOTAL', 'Total'))],
use_table.iloc[:, :use_table.columns.get_loc(('TOTAL', 'Total'))].sum(axis=1), atol=1e-5)
assert np.allclose(supply_table.iloc[supply_table.index.get_loc(('TOTAL', 'Total'))],
supply_table.iloc[:supply_table.index.get_loc(('TOTAL', 'Total'))].sum(), atol=1e-5)
# extract the tables we need
W = use_table.loc[self.factors_of_production, self.industries]
W.drop(('GVA', 'Gross value-added at basic prices'), inplace=True)
Y = use_table.loc[self.commodities, final_demand]
WY = use_table.loc[self.factors_of_production, final_demand]
WY.drop(('GVA', 'Gross value-added at basic prices'), inplace=True)
g = use_table.loc[[('TOTAL', 'Total')], self.industries]
q = supply_table.loc[self.commodities, [('TOTAL', 'Total')]]
V = supply_table.loc[self.commodities, self.industries]
U = use_table.loc[self.commodities, self.industries]
INT_imports = supply_table.loc[self.commodities, [('INTIM000', 'International imports')]]
# create multiindex with region as first level
for matrix in [W, Y, WY, g, q, V, U, INT_imports]:
matrix.columns = pd.MultiIndex.from_product([[region], matrix.columns]).tolist()
matrix.index = pd.MultiIndex.from_product([[region], matrix.index]).tolist()
# concat the region tables with the all the other tables
self.W = pd.concat([self.W, W])
self.WY = pd.concat([self.WY, WY])
self.Y = pd.concat([self.Y, Y])
self.q = pd.concat([self.q, q])
self.g = pd.concat([self.g, g])
self.U = pd.concat([self.U, U])
self.V = pd.concat([self.V, V])
self.INT_imports = pd.concat([self.INT_imports, INT_imports])
def dealing_with_duplicated_names(self):
"""
IOIC classification has duplicate names, so we rename when it's the case
:return: updated dataframes
"""
# reindexing to fix the order of the columns
self.V = self.V.T.reindex(pd.MultiIndex.from_product([self.matching_dict.keys(), self.industries]).tolist()).T
self.U = self.U.T.reindex(pd.MultiIndex.from_product([self.matching_dict.keys(), self.industries]).tolist()).T
self.g = self.g.T.reindex(pd.MultiIndex.from_product([self.matching_dict.keys(), self.industries]).tolist()).T
self.W = self.W.T.reindex(pd.MultiIndex.from_product([self.matching_dict.keys(), self.industries]).tolist()).T
if self.level_of_detail in ['Link-1961 level', 'Link-1997 level', 'Detail level']:
self.industries = [(i[0], i[1] + ' (private)') if re.search(r'^BS61', i[0]) else i for i in
self.industries]
self.industries = [(i[0], i[1] + ' (non-profit)') if re.search(r'^NP61|^NP71', i[0]) else i for i in
self.industries]
self.industries = [(i[0], i[1] + ' (public)') if re.search(r'^GS61', i[0]) else i for i in
self.industries]
if self.level_of_detail in ['Link-1997 level', 'Detail level']:
self.industries = [(i[0], i[1] + ' (private)') if re.search(r'^BS623|^BS624', i[0]) else i for i in
self.industries]
self.industries = [(i[0], i[1] + ' (non-profit)') if re.search(r'^NP624', i[0]) else i for i in
self.industries]
self.industries = [(i[0], i[1] + ' (public)') if re.search(r'^GS623', i[0]) else i for i in
self.industries]
# applying the change of names to columns
for df in [self.V, self.U, self.g, self.W]:
df.columns = pd.MultiIndex.from_product([self.matching_dict.keys(), self.industries]).tolist()
def organize_final_demand(self):
"""
Extract the final demand sectors. These will be disaggregated. If you do not want the detail, use
self.aggregated_final_demand()
Provincial exports will be included in self.U and are thus excluded from self.Y
:return: self.Y & self.WY updated
"""
# dealing with duplicate names of disaggregated final demand sector names separately
self.Y.columns = [(i[0], (i[1][0], i[1][1] + ' (private)')) if re.search(r'^COB61|^MEB61|^IPB61|^MEBU', i[1][0])
else i for i in self.Y.columns]
self.Y.columns = [(i[0], (i[1][0], i[1][1] + ' (public)')) if re.search(r'^COG61|^MEG61|^IPG61|^MEGU', i[1][0])
else i for i in self.Y.columns]
self.Y.columns = [(i[0], (i[1][0], i[1][1] + ' (non-profit)')) if re.search(r'^MENU', i[1][0])
else i for i in self.Y.columns]
self.WY.columns = [(i[0], (i[1][0], i[1][1] + ' (private)')) if re.search(r'^COB61|^MEB61|^IPB61|^MEBU', i[1][0])
else i for i in self.WY.columns]
self.WY.columns = [(i[0], (i[1][0], i[1][1] + ' (public)')) if re.search(r'^COG61|^MEG61|^IPG61|^MEGU', i[1][0])
else i for i in self.WY.columns]
self.WY.columns = [(i[0], (i[1][0], i[1][1] + ' (non-profit)')) if re.search(r'^MENU', i[1][0])
else i for i in self.WY.columns]
Y = pd.DataFrame()
fd_households = [i for i in self.Y.columns if re.search(r'^PEC\w*\d', i[1][0])]
df = self.Y.loc[:, fd_households].copy()
df.columns = [(i[0], "Household final consumption expenditure", i[1][1]) for i in fd_households]
Y = pd.concat([Y, df], axis=1)
fd_npish = [i for i in self.Y.columns if re.search(r'^CEN\w*\d', i[1][0])]
df = self.Y.loc[:, fd_npish].copy()
df.columns = [(i[0], i[1][1], 'NPISH') for i in fd_npish]
Y = pd.concat([Y, df], axis=1)
fd_gov = [i for i in self.Y.columns if re.search(r'^CEG\w*\d', i[1][0])]
df = self.Y.loc[:, fd_gov].copy()
df.columns = [(i[0], "Governments final consumption expenditure", i[1][1]) for i in fd_gov]
Y = pd.concat([Y, df], axis=1)
fd_construction = [i for i in self.Y.columns if re.search(r'^CO\w*\d', i[1][0])]
df = self.Y.loc[:, fd_construction].copy()
df.columns = [(i[0], "Gross fixed capital formation, Construction", i[1][1]) for i in fd_construction]
Y = pd.concat([Y, df], axis=1)
fd_machinery = [i for i in self.Y.columns if re.search(r'^ME\w*\d', i[1][0])]
df = self.Y.loc[:, fd_machinery].copy()
df.columns = [(i[0], "Gross fixed capital formation, Machinery and equipment", i[1][1]) for i in fd_machinery]
Y = pd.concat([Y, df], axis=1)
fd_ip = [i for i in self.Y.columns if re.search(r'^IP\w[T]*\d', i[1][0])]
df = self.Y.loc[:, fd_ip].copy()
df.columns = [(i[0], "Gross fixed capital formation, Intellectual property products", i[1][1]) for i in fd_ip]
Y = pd.concat([Y, df], axis=1)
fd_inv = [i for i in self.Y.columns if re.search(r'^INV\w*\d', i[1][0])]
df = self.Y.loc[:, fd_inv].copy()
df.columns = [(i[0], "Changes in inventories", i[1][1]) for i in fd_inv]
Y = pd.concat([Y, df], axis=1)
fd_int = [i for i in self.Y.columns if re.search(r'^INT\w*', i[1][0])]
df = self.Y.loc[:, fd_int].copy()
df.columns = [(i[0], "International exports", i[1][1].split(' ')[1].capitalize()) for i in fd_int]
Y = pd.concat([Y, df], axis=1)
self.Y = Y
WY = pd.DataFrame()
fd_households = [i for i in self.WY.columns if re.search(r'^PEC\w*\d', i[1][0])]
df = self.WY.loc[:, fd_households].copy()
df.columns = [(i[0], "Household final consumption expenditure", i[1][1]) for i in fd_households]
WY = pd.concat([WY, df], axis=1)
fd_npish = [i for i in self.WY.columns if re.search(r'^CEN\w*\d', i[1][0])]
df = self.WY.loc[:, fd_npish].copy()
df.columns = [(i[0], i[1][1], 'NPISH') for i in fd_npish]
WY = pd.concat([WY, df], axis=1)
fd_gov = [i for i in self.WY.columns if re.search(r'^CEG\w*\d', i[1][0])]
df = self.WY.loc[:, fd_gov].copy()
df.columns = [(i[0], "Governments final consumption expenditure", i[1][1]) for i in fd_gov]
WY = pd.concat([WY, df], axis=1)
fd_construction = [i for i in self.WY.columns if re.search(r'^CO\w*\d', i[1][0])]
df = self.WY.loc[:, fd_construction].copy()
df.columns = [(i[0], "Gross fixed capital formation, Construction", i[1][1]) for i in fd_construction]
WY = pd.concat([WY, df], axis=1)
fd_machinery = [i for i in self.WY.columns if re.search(r'^ME\w*\d', i[1][0])]
df = self.WY.loc[:, fd_machinery].copy()
df.columns = [(i[0], "Gross fixed capital formation, Machinery and equipment", i[1][1]) for i in fd_machinery]
WY = pd.concat([WY, df], axis=1)
fd_ip = [i for i in self.WY.columns if re.search(r'^IP\w[T]*\d', i[1][0])]
df = self.WY.loc[:, fd_ip].copy()
df.columns = [(i[0], "Gross fixed capital formation, Intellectual property products", i[1][1]) for i in fd_ip]
WY = pd.concat([WY, df], axis=1)
fd_inv = [i for i in self.WY.columns if re.search(r'^INV\w*\d', i[1][0])]
df = self.WY.loc[:, fd_inv].copy()
df.columns = [(i[0], "Changes in inventories", i[1][1]) for i in fd_inv]
WY = pd.concat([WY, df], axis=1)
fd_int = [i for i in self.WY.columns if re.search(r'^INT\w*', i[1][0])]
df = self.WY.loc[:, fd_int].copy()
df.columns = [(i[0], "International exports", i[1][1].split(' ')[1].capitalize()) for i in fd_int]
WY = pd.concat([WY, df], axis=1)
self.WY = WY
assert np.isclose((self.U.sum(1) + self.Y.sum(1) - self.INT_imports.sum(1)).sum(), self.q.sum(1).sum())
def remove_codes(self):
"""
Removes the IOIC codes from the index to only leave the name.
:return: Dataframes with the code of the multi-index removed
"""
# removing the IOIC codes
for df in [self.W, self.g, self.V, self.U, self.INT_imports]:
df.columns = [(i[0], i[1][1]) for i in df.columns]
for df in [self.W, self.Y, self.WY, self.q, self.V, self.U, self.INT_imports]:
df.index = [(i[0], i[1][1]) for i in df.index]
# recreating MultiIndexes
for df in [self.W, self.Y, self.WY, self.g, self.q, self.V, self.U, self.INT_imports]:
df.index = pd.MultiIndex.from_tuples(df.index)
df.columns = pd.MultiIndex.from_tuples(df.columns)
# reordering columns
reindexed_columns = pd.MultiIndex.from_product([self.matching_dict.keys(), [i[1] for i in self.industries]])
self.W = self.W.T.reindex(reindexed_columns).T
self.g = self.g.T.reindex(reindexed_columns).T
self.V = self.V.T.reindex(reindexed_columns).T
self.U = self.U.T.reindex(reindexed_columns).T
def endogenizing_capitals(self):
"""
Endogenize gross fixed capital formation (GFCF) of openIO-Canada. Take the final demand for GFCF and distribute
it to the different sectors of the economy requiring the purchase of these capital goods.
Because capitals are endogenized they also need to be removed from the final demand except for residential
buildings which are kept as a final demand.
:return:
"""
endo = pd.read_excel(pkg_resources.resource_stream(__name__, '/Data/Concordances/Endogenizing.xlsx'))
self.K = pd.DataFrame(0, self.U.index, self.U.columns, float)
for province in self.matching_dict.keys():
for capital_type in ['Gross fixed capital formation, Construction',
'Gross fixed capital formation, Machinery and equipment',
'Gross fixed capital formation, Intellectual property products']:
df = self.Y.loc(axis=1)[province, capital_type]
for capital in df.columns:
if self.V.loc[:, province].loc[:, endo[endo.Capitals == capital].loc[:, 'IOIC']].sum().sum() != 0:
share = (self.V.loc[:, province].loc[:, endo[endo.Capitals == capital].loc[:, 'IOIC']].sum() /
self.V.loc[:, province].loc[:,
endo[endo.Capitals == capital].loc[:, 'IOIC']].sum().sum())
for sector in share.index:
self.K.loc[:, (province, sector)] += (df.loc[:, capital] * share.loc[sector])
elif (self.Y.loc(axis=1)[province, capital_type, capital].sum() != 0 and
capital not in ['Residential structures', 'Used cars and equipment and scrap (private)',
'Used cars and equipment and scrap (public)',
'Used cars and equipment and scrap (non-profit)']):
if len(endo[endo.Capitals == capital].loc[:, 'IOIC']) == 1:
self.K.loc[:, (province, endo[endo.Capitals == capital].loc[:, 'IOIC'].iloc[0])] += df.loc[:,capital]
else:
warnings.warn('There is more capital ' + capital + ' for the province: ' + province +
' purchased than total purchases of the corresponding sector in that year.')
# add a final demand category for households for building residential structures
df = self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Construction', 'Residential structures'].copy('deep')
df.columns = pd.MultiIndex.from_product([self.matching_dict.keys(),
['Household final consumption expenditure'],
['Residential structures']])
self.Y = pd.concat([self.Y, df], axis=1)
# add a final demand category for changes in inventories for Used cars and equipment and scrap
df = self.Y.loc(axis=1)[:, :, ['Used cars and equipment and scrap (private)',
'Used cars and equipment and scrap (public)',
'Used cars and equipment and scrap (non-profit)']].copy('deep')
df = df.T.groupby(level=0).sum().T
df.columns = pd.MultiIndex.from_product([self.matching_dict.keys(), ['Changes in inventories'],
['Changes in inventories, used cars and equipment and scrap']])
self.Y = pd.concat([self.Y, df], axis=1)
# check that all capitals were either added to K or moved to Households/Inventories
assert np.isclose(self.Y.loc(axis=1)[:, ['Gross fixed capital formation, Construction',
'Gross fixed capital formation, Machinery and equipment',
'Gross fixed capital formation, Intellectual property products']].sum().sum(),
(self.K.sum().sum() + self.Y.loc(axis=1)[:, 'Household final consumption expenditure',
'Residential structures'].sum().sum() +
self.Y.loc(axis=1)[:, 'Changes in inventories',
'Changes in inventories, used cars and equipment and scrap'].sum().sum()))
# drop capitals from final demand
self.Y = self.Y.drop([i for i in self.Y.columns if (
i[1] in ['Gross fixed capital formation, Construction',
'Gross fixed capital formation, Machinery and equipment',
'Gross fixed capital formation, Intellectual property products'])], axis=1)
self.Y.columns = pd.MultiIndex.from_tuples(self.Y.columns)
assert np.isclose((self.U.sum(1) + self.K.sum(1) + self.Y.sum(1) - self.INT_imports.sum(1)).sum(),
self.q.sum(1).sum())
# correct added value to account for the fact that capitals were endogenized
capital_added_value_removal = pd.concat([-self.K.sum()] * len(self.matching_dict), axis=1).T
capital_added_value_removal.index = pd.MultiIndex.from_product(
[self.matching_dict.keys(), ['Capital endogenization removal']])
for province in self.matching_dict.keys():
capital_added_value_removal.loc[[i for i in self.matching_dict.keys() if i != province], province] = 0
self.W = pd.concat([self.W, capital_added_value_removal])
assert np.isclose((self.U.sum() + self.K.sum() + self.W.sum()).sum(), self.g.sum().sum())
def province_import_export(self, province_trade_file):
"""
Method extracting and formatting inter province imports/exports
:return: modified self.U, self.V, self.W, self.Y
"""
province_trade_file = province_trade_file
province_trade_file.Origin = [{v: k for k, v in self.matching_dict.items()}[i.split(') ')[1]] if ')' in i
else i for i in province_trade_file.Origin]
province_trade_file.Destination = [{v: k for k, v in self.matching_dict.items()}[i.split(') ')[1]] if ')' in i
else i for i in province_trade_file.Destination]
# extracting and formatting supply for each province
province_trade = pd.pivot_table(data=province_trade_file, index='Destination', columns=['Origin', 'Product'])
province_trade = province_trade.loc[
[i for i in province_trade.index if i in self.matching_dict.keys()],
[i for i in province_trade.columns if i[1] in self.matching_dict.keys()]]
if self.level_of_detail == 'Detail level':
province_trade *= 1000
else:
province_trade *= 1000000
province_trade.columns = [(i[1], i[2].split(': ')[1]) if ':' in i[2] else i for i in
province_trade.columns]
province_trade.drop([i for i in province_trade.columns if i[1] not in [i[1] for i in self.commodities]],
axis=1, inplace=True)
province_trade.columns = pd.MultiIndex.from_tuples(province_trade.columns)
for province in province_trade.index:
province_trade.loc[province, province] = 0
import_markets = pd.DataFrame(0, province_trade.index, province_trade.columns, float)
for importing_province in province_trade.index:
for exported_product in province_trade.columns.levels[1]:
exported_products = [i for i in import_markets.columns if i[1] == exported_product]
import_markets.loc[importing_province, exported_products] = (
province_trade.loc[importing_province, exported_products] /
province_trade.loc[importing_province, exported_products].sum()).values
before_distribution_U = self.U.copy('deep')
before_distribution_K = self.K.copy('deep')
before_distribution_Y = self.Y.copy('deep')
if not self.endogenizing:
for importing_province in province_trade.index:
total_use = pd.concat([self.U.loc[importing_province, importing_province],
self.Y.loc[importing_province, importing_province]], axis=1)
total_imports = province_trade.T.groupby(level=1).sum().T.loc[importing_province]
index_commodity = [i[1] for i in self.commodities]
total_imports = total_imports.reindex(index_commodity).fillna(0)
import_distribution_U = ((self.U.loc[importing_province, importing_province].T /
(total_use.sum(axis=1))) *
total_imports).T.fillna(0)
import_distribution_Y = ((self.Y.loc[importing_province, importing_province].T /
(total_use.sum(axis=1))) *
total_imports).T.fillna(0)
# distribution balance imports to the different exporting regions
for exporting_province in province_trade.index:
if importing_province != exporting_province:
scaled_imports_U = ((import_distribution_U.T * import_markets.fillna(0).loc[
importing_province, exporting_province]).T).reindex(import_distribution_U.index).fillna(0)
scaled_imports_Y = ((import_distribution_Y.T * import_markets.fillna(0).loc[
importing_province, exporting_province]).T).reindex(import_distribution_Y.index).fillna(0)
self.assert_order(exporting_province, importing_province, scaled_imports_U, scaled_imports_Y)
# assign new values into self.U
self.U.loc[exporting_province, importing_province] = (
scaled_imports_U.loc[:, self.U.columns.levels[1]].reindex(
self.U.loc[exporting_province, importing_province].columns, axis=1).values)
# assign new values into self.Y
self.Y.loc[exporting_province, importing_province] = (
scaled_imports_Y.loc[:, self.Y.columns.levels[1]].reindex(
self.Y.loc[exporting_province, importing_province].columns, axis=1).values)
# remove interprovincial from intraprovincial to not double count
self.U.loc[importing_province, importing_province] = (
self.U.loc[importing_province, importing_province] - self.U.loc[
[i for i in self.matching_dict if i != importing_province], importing_province].groupby(
level=1).sum()).reindex([i[1] for i in self.commodities]).values
self.Y.loc[importing_province, importing_province] = (
self.Y.loc[importing_province, importing_province] - self.Y.loc[
[i for i in self.matching_dict if i != importing_province], importing_province].groupby(
level=1).sum()).reindex([i[1] for i in self.commodities]).values
# if some province buys more than they use, drop the value in "changes in inventories"
df = self.U[self.U < -1].dropna(how='all', axis=1).dropna(how='all')
if len(df):
self.Y.loc[:, (importing_province, 'Changes in inventories',
'Changes in inventories, finished goods and goods in process')] += (
df.sum(1).reindex(self.Y.index).fillna(0))
self.U.loc[df.index, df.columns] = 0
# removing negative values lower than 1$ (potential calculation artefacts)
self.U = self.U[self.U > 0].fillna(0)
# checking negative values were removed
assert not self.U[self.U < 0].any().any()
# check that the distribution went smoothly
assert np.isclose(self.U.sum().sum()+self.Y.sum().sum(),
before_distribution_U.sum().sum()+before_distribution_Y.sum().sum())
else:
for importing_province in province_trade.index:
total_use = pd.concat([self.U.loc[importing_province, importing_province] +
self.K.loc[importing_province, importing_province],
self.Y.loc[importing_province, importing_province]], axis=1)
total_imports = province_trade.T.groupby(level=1).sum().T.loc[importing_province]
index_commodity = [i[1] for i in self.commodities]
total_imports = total_imports.reindex(index_commodity).fillna(0)
import_distribution_U = ((self.U.loc[importing_province, importing_province].T /
(total_use.sum(axis=1))) *
total_imports).T.fillna(0)
import_distribution_K = ((self.K.loc[importing_province, importing_province].T /
(total_use.sum(axis=1))) *
total_imports).T.fillna(0)
import_distribution_Y = ((self.Y.loc[importing_province, importing_province].T /
(total_use.sum(axis=1))) *
total_imports).T.fillna(0)
# distribution balance imports to the different exporting regions
for exporting_province in province_trade.index:
if importing_province != exporting_province:
scaled_imports_U = ((import_distribution_U.T * import_markets.fillna(0).loc[
importing_province, exporting_province]).T).reindex(import_distribution_U.index).fillna(0)
scaled_imports_K = ((import_distribution_K.T * import_markets.fillna(0).loc[
importing_province, exporting_province]).T).reindex(import_distribution_K.index).fillna(0)
scaled_imports_Y = ((import_distribution_Y.T * import_markets.fillna(0).loc[
importing_province, exporting_province]).T).reindex(import_distribution_Y.index).fillna(0)
self.assert_order(exporting_province, importing_province, scaled_imports_U, scaled_imports_Y,
scaled_imports_K)
# assign new values into self.U
self.U.loc[exporting_province, importing_province] = (
scaled_imports_U.loc[:, self.U.columns.levels[1]].reindex(
self.U.loc[exporting_province, importing_province].columns, axis=1).values)
# assign new values into self.K
self.K.loc[exporting_province, importing_province] = (
scaled_imports_K.loc[:, self.K.columns.levels[1]].reindex(
self.K.loc[exporting_province, importing_province].columns, axis=1).values)
# assign new values into self.Y
self.Y.loc[exporting_province, importing_province] = (
scaled_imports_Y.loc[:, self.Y.columns.levels[1]].reindex(
self.Y.loc[exporting_province, importing_province].columns, axis=1).values)
# remove interprovincial from intraprovincial to not double count
self.U.loc[importing_province, importing_province] = (
self.U.loc[importing_province, importing_province] - self.U.loc[
[i for i in self.matching_dict if i != importing_province], importing_province].groupby(
level=1).sum()).reindex([i[1] for i in self.commodities]).values
self.K.loc[importing_province, importing_province] = (
self.K.loc[importing_province, importing_province] - self.K.loc[
[i for i in self.matching_dict if i != importing_province], importing_province].groupby(
level=1).sum()).reindex([i[1] for i in self.commodities]).values
self.Y.loc[importing_province, importing_province] = (
self.Y.loc[importing_province, importing_province] - self.Y.loc[
[i for i in self.matching_dict if i != importing_province], importing_province].groupby(
level=1).sum()).reindex([i[1] for i in self.commodities]).values
# if some province buys more than they use, drop the value in "changes in inventories"
df = self.U[self.U < -1].dropna(how='all', axis=1).dropna(how='all')
if len(df):
self.Y.loc[:, (importing_province, 'Changes in inventories',
'Changes in inventories, finished goods and goods in process')] += (
df.sum(1).reindex(self.Y.index).fillna(0))
self.U.loc[df.index, df.columns] = 0
# removing negative values lower than 1$ (potential calculation artefacts)
self.U = self.U[self.U > 0].fillna(0)
self.K = self.K[self.K > 0].fillna(0)
# checking negative values were removed
assert not self.U[self.U < 0].any().any()
assert not self.K[self.K < 0].any().any()
# check that the distribution went smoothly
assert np.isclose(self.U.sum().sum()+self.K.sum().sum()+self.Y.sum().sum(),
before_distribution_U.sum().sum()+before_distribution_K.sum().sum()+before_distribution_Y.sum().sum())
def determine_sectors_importing(self):
"""
Determine which sectors use international imports and removing international imports from use
:return:
"""
# aggregating international imports in 1 column
self.INT_imports = self.INT_imports.T.groupby(level=1).sum().T
# save total values to check if distribution was done properly later
before_distribution_U = self.U.sum().sum()
before_distribution_K = self.K.sum().sum()
before_distribution_Y = self.Y.sum().sum()
# need to flatten multiindex for the concatenation to work properly
self.Y.columns = self.Y.columns.tolist()
self.U.columns = self.U.columns.tolist()
self.K.columns = self.K.columns.tolist()
# determine total use
if not self.endogenizing:
total_use = pd.concat([self.U, self.Y], axis=1)
else:
total_use = pd.concat([self.U + self.K, self.Y], axis=1)
# weighted average of who is requiring the international imports, based on national use
self.who_uses_int_imports_U = (self.U.T / total_use.sum(1)).fillna(0).T * self.INT_imports.values
self.who_uses_int_imports_Y = (self.Y.T / total_use.sum(1)).fillna(0).T * self.INT_imports.values
if self.endogenizing:
self.who_uses_int_imports_K = (self.K.T / total_use.sum(1)).fillna(0).T * self.INT_imports.values
# remove international imports from national use
self.U = self.U - self.who_uses_int_imports_U.reindex(self.U.columns, axis=1)
self.Y = self.Y - self.who_uses_int_imports_Y.reindex(self.Y.columns, axis=1)
if self.endogenizing:
self.K = self.K - self.who_uses_int_imports_K.reindex(self.K.columns, axis=1)
# check totals match
assert np.isclose(self.U.sum().sum() + self.who_uses_int_imports_U.sum().sum(), before_distribution_U)
assert np.isclose(self.K.sum().sum() + self.who_uses_int_imports_K.sum().sum(), before_distribution_K)
assert np.isclose(self.Y.sum().sum() + self.who_uses_int_imports_Y.sum().sum(), before_distribution_Y)
# check that nothing fuzzy is happening with negative values that are not due to artefacts
if not len(self.U[self.U < -1].dropna(how='all', axis=1).dropna(how='all', axis=0)) == 0:
warnings.warn("Warning! The import data for the following sectors is inconsistent with the supply and use "
"data and stipulates that these sectors import more than what they are using "+
str([i for i in self.U[self.U < -1].dropna(how='all', axis=1).dropna(how='all', axis=0).index])+
". The resulting negative values will be forced to zero.")
# remove negative artefacts (like 1e-10$)
self.U = self.U[self.U > 0].fillna(0)
assert not self.U[self.U < 0].any().any()
self.K = self.K[self.K > 0].fillna(0)
assert not self.K[self.K < 0].any().any()
# remove negative artefacts
self.Y = pd.concat([self.Y[self.Y >= 0].fillna(0), self.Y[self.Y < -1].fillna(0)], axis=1)
self.Y = self.Y.T.groupby(by=self.Y.columns).sum().T
self.Y.columns = pd.MultiIndex.from_tuples(self.Y.columns)
def load_merchandise_international_trade_database(self):
"""
Loading and treating the international trade merchandise database of Statistics Canada.
Original source: https://open.canada.ca/data/en/dataset/b1126a07-fd85-4d56-8395-143aba1747a4
:return:
"""
# load concordance between HS classification and IOIC classification
conc = pd.read_excel(pkg_resources.resource_stream(__name__, '/Data/Concordances/HS-IOIC.xlsx'))
# load database
merchandise_database = pd.read_excel(pkg_resources.resource_stream(__name__, '/Data/Imports_data/Imports_' +
str(self.year) + '_HS06_treated.xlsx'))
merchandise_database = merchandise_database.ffill()
merchandise_database.columns = ['Country', 'HS6', 'Value']
# apply concordance
merchandise_database = merchandise_database.merge(conc, on='HS6', how='left')
# only keep useful information
merchandise_database = merchandise_database.loc[:, ['IOIC', 'Country', 'Value']]
# remove HS sectors that cannot be matched to IOIC
merchandise_database = merchandise_database.drop([i for i in merchandise_database.index
if merchandise_database.loc[i, 'IOIC'] == 'None']).dropna(subset=['IOIC'])
# change IOIC codes to sector names
code_to_name = {j[0]: j[1] for j in self.commodities}
merchandise_database.IOIC = [code_to_name[i] for i in merchandise_database.IOIC]
# set MultiIndex with country and classification
merchandise_database = merchandise_database.set_index(['Country', 'IOIC'])
# regroup purchases together (on country + IOIC sector)
merchandise_database = merchandise_database.groupby(merchandise_database.index).sum()
# set Multi-index
merchandise_database.index = pd.MultiIndex.from_tuples(merchandise_database.index)
# reset the index to apply country converter
merchandise_database = merchandise_database.reset_index()
# apply country converter
merchandise_database.level_0 = coco.convert(merchandise_database.level_0, to='EXIO3')
# restore index
merchandise_database = merchandise_database.set_index(['level_0', 'level_1'])
merchandise_database.index.names = None, None
# groupby on country/sector (e.g., there were multiple 'WL' after applying coco)
merchandise_database = merchandise_database.groupby(merchandise_database.index).sum()
# restore multi-index
merchandise_database.index = pd.MultiIndex.from_tuples(merchandise_database.index)
# reindexing to ensure all sectors are here, fill missing ones with zero values
self.merchandise_imports = merchandise_database.reindex(pd.MultiIndex.from_product([
merchandise_database.index.levels[0], [i[1] for i in self.commodities]])).fillna(0)
def link_merchandise_database_to_openio(self):
"""
Linking the international trade merchandise database of Statistics Canada to openIO-Canada.
:return:
"""
# the absolute values of self.merchandise_imports do not matter
# we only use those to calculate a weighted average of imports per country
for product in self.merchandise_imports.index.levels[1]:
total = self.merchandise_imports.loc(axis=0)[:, product].sum()
for region in self.merchandise_imports.index.levels[0]:
self.merchandise_imports.loc(axis=0)[region, product] /= total
# Nan values showing up from 0/0 operations
self.merchandise_imports = self.merchandise_imports.fillna(0)
def scale_international_imports(who_uses_int_imports, matrix):
df = who_uses_int_imports.groupby(level=1).sum()
df = pd.concat([df] * len(self.merchandise_imports.index.levels[0]))
df.index = pd.MultiIndex.from_product([self.merchandise_imports.index.levels[0],
who_uses_int_imports.index.levels[1]])
for product in self.merchandise_imports.index.levels[1]:
dff = (df.loc(axis=0)[:, product].T * self.merchandise_imports.loc(axis=0)[:, product].iloc[:, 0]).T
if matrix == 'U':
self.merchandise_imports_scaled_U = pd.concat([self.merchandise_imports_scaled_U, dff])
if matrix == 'K':
self.merchandise_imports_scaled_K = pd.concat([self.merchandise_imports_scaled_K, dff])
if matrix == 'Y':
self.merchandise_imports_scaled_Y = pd.concat([self.merchandise_imports_scaled_Y, dff])
scale_international_imports(self.who_uses_int_imports_U, 'U')
scale_international_imports(self.who_uses_int_imports_Y, 'Y')
if self.endogenizing:
scale_international_imports(self.who_uses_int_imports_K, 'K')
self.merchandise_imports_scaled_U = self.merchandise_imports_scaled_U.sort_index()
self.merchandise_imports_scaled_Y = self.merchandise_imports_scaled_Y.sort_index()
if self.endogenizing:
self.merchandise_imports_scaled_K = self.merchandise_imports_scaled_K.sort_index()
def gimme_symmetric_iot(self):
"""
Transforms Supply and Use tables to symmetric IO tables and transforms Y from product to industries if
selected classification is "industry"
:return: self.A, self.R and self.Y
"""
# recalculate g because we introduced K
if self.endogenizing:
g = (self.U.sum() + self.W.sum() + self.who_uses_int_imports_U.sum() + self.K.sum() +
self.who_uses_int_imports_K.sum())
g = pd.concat([g] * len(self.matching_dict), axis=1).T
g.index = self.g.index
g.columns = pd.MultiIndex.from_tuples(g.columns)
for province in self.matching_dict.keys():
g.loc[[i for i in g.index.levels[0] if i != province], province] = 0
self.g = g.copy('deep')
self.inv_q = pd.DataFrame(np.diag((1 / self.q.sum(axis=1)).replace(np.inf, 0)), self.q.index, self.q.index)
self.inv_g = pd.DataFrame(np.diag((1 / self.g.sum()).replace(np.inf, 0)), self.g.columns, self.g.columns)
self.A = self.U.dot(self.inv_g.dot(self.V.T)).dot(self.inv_q)
self.R = self.W.dot(self.inv_g.dot(self.V.T)).dot(self.inv_q)
if self.exiobase_folder:
self.merchandise_imports_scaled_U = self.merchandise_imports_scaled_U.reindex(
self.U.columns, axis=1).dot(self.inv_g.dot(self.V.T)).dot(self.inv_q)
self.merchandise_imports_scaled_K = self.merchandise_imports_scaled_K.reindex(
self.U.columns, axis=1).dot(self.inv_g.dot(self.V.T)).dot(self.inv_q)
if self.endogenizing:
self.K = self.K.dot(self.inv_g.dot(self.V.T)).dot(self.inv_q)
def link_international_trade_data_to_exiobase(self):
"""
Linking the data from the international merchandise trade database, which was previously linked to openIO-Canada,
to exiobase.
:return:
"""
# loading Exiobase
io = pymrio.parse_exiobase3(self.exiobase_folder)
if self.endogenizing:
with gzip.open(pkg_resources.resource_stream(
__name__, '/Data/Capitals_endogenization_exiobase/K_cfc_pxp_exio3.8.2_' +
str(self.year) + '.gz.pickle'), 'rb') as f:
self.K_exio = pickle.load(f)
# save the matrices from exiobase because we need them later
self.A_exio = io.A.copy('deep')
self.Z_exio = io.Z.copy('deep')
self.x_exio = io.x.copy('deep')
self.S_exio = io.satellite.S.copy('deep')
self.F_exio = io.satellite.F.copy('deep')