-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathopenIO.py
More file actions
3698 lines (3194 loc) · 221 KB
/
openIO.py
File metadata and controls
3698 lines (3194 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Class that creates symmetric Input-Output tables for Canada and its provinces
author: maxime.agez@polymtl.ca
"""
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=True):
"""
: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
: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
self.folder_path = folder_path
# 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.Y_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.imports = pd.DataFrame()
self.imports_scaled_U = pd.DataFrame()
self.imports_scaled_K = pd.DataFrame()
self.imports_scaled_Y = pd.DataFrame()
self.minerals = pd.DataFrame()
self.emission_factors_basic_price = pd.DataFrame()
self.emission_factors_purchaser_price = 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])
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'))
logger.info("Loading Exiobase...")
self.load_exiobase()
logger.info('Treatment of international trade data...')
self.determine_sectors_importing()
self.load_and_correct_international_trade_data()
logger.info("Linking international trade data to openIO-Canada...")
self.link_imports_to_openio()
logger.info("Building the symmetric tables...")
self.gimme_symmetric_iot()
logger.info("Linking openIO-Canada to Exiobase...")
self.link_international_trade_data_to_exiobase()
self.remove_abroad_enclaves()
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...")
self.match_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, 2021, 2022]:
# 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']
tables = [supply_table, use_table]
for i, table in enumerate(tables):
df = table.iloc[starting_line_values - 2:, 2:]
df.index = list(zip(table.iloc[starting_line_values - 2:, 0].tolist(),
table.iloc[starting_line_values - 2:, 1].tolist()))
df.columns = list(zip(table.iloc[starting_line + 1, 2:].tolist(),
table.iloc[starting_line, 2:].tolist()))
df = df.astype(str).replace(to_replace=['.'], value='0').astype(float)
tables[i] = df # Update the corresponding table in the list
# Unpack the tables back into their original variables
supply_table, use_table = tables
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 consumption of fixed capitals (CFC) of openIO-Canada. CFC is not directly available in the supply
and use tables of StatCan. However, it is available at the total provincial level. For openIO-Canada, we want
this data per province AND per sector AND we want the detail of what kind of capital good was purchased.
So how do we redistribute the provincial values that we have to all sectors while keeping the inputs detail?
We first derive historical gross fixed capital formation over the years 2014 to the latest available year from
the SUTs. We get the average capital goods built over these last years. This distribution is then scaled to
the provincial totals. This gives the CFC per sector per province. To get the inputs details (i.e., to know if
it's a car or a laptop that was bought) we then apply the reference year GFCF (Gross fixed capital formation)
distribution from the SUTs.
Note that we excluded Used car and equipment from the GFCF and the CFC and put it in a newly created Changes in
inventories category.
We also replace the Gross operating surplus value added category by the Net operating surplus, which is the
difference between the Gross operating surplus and the estimated CFC. Negative values of Net operating surplus
simply indicate that the whole sector in that province that year operated at a loss.
:return:
"""
# load historical gross fixed capital formation (generated with SUTs from 2014 to 2021)
hist_gfcf = pd.read_excel(pkg_resources.resource_stream(
__name__, '/Data/Capitals_endogenization/historical_gross_fixed_capital_formation.xlsx'), index_col=0)
hist_gfcf.index = pd.MultiIndex.from_tuples([eval(i) for i in hist_gfcf.index])
hist_gfcf.columns = pd.MultiIndex.from_tuples([eval(i) for i in hist_gfcf.columns])
# change of classification requires some adjustments in the historical gfcf values
if self.year == 2022:
hist_gfcf.columns = pd.MultiIndex.from_tuples(
[(i[0], 'Other Indigenous government services') if i[1] == 'Other aboriginal government services' else i
for i in hist_gfcf.columns])
hist_gfcf.columns = pd.MultiIndex.from_tuples(
[(i[0], 'Animal production and aquaculture') if i[1] == 'Animal production' else i for i in
hist_gfcf.columns])
hist_gfcf.columns = pd.MultiIndex.from_tuples(
[(i[0].replace('2111A', '21111'), i[1]) if '2111A' in i[0] else i for i in hist_gfcf.columns])
hist_gfcf.columns = pd.MultiIndex.from_tuples(
[(i[0].replace('2111B', '21114'), i[1]) if '2111B' in i[0] else i for i in hist_gfcf.columns])
hist_gfcf.columns = pd.MultiIndex.from_tuples(
[(i[0].replace('55100', '55000'), i[1]) if '55100' in i[0] else i for i in hist_gfcf.columns])
df = pd.concat([hist_gfcf.loc[:, 'COG61000']] * 3, axis=1)
df.columns = pd.MultiIndex.from_tuples([('COG61110', 'Elementary and secondary schools'),
('COG61120', 'Community colleges and C.E.G.E.P.s'),
('COG61130', 'Universities')])
hist_gfcf = hist_gfcf.drop('COG61000', axis=1).join(df)
df = pd.concat([hist_gfcf.loc[:, 'MEG61000']] * 3, axis=1)
df.columns = pd.MultiIndex.from_tuples([('MEG61110', 'Elementary and secondary schools'),
('MEG61120', 'Community colleges and C.E.G.E.P.s'),
('MEG61130', 'Universities')])
hist_gfcf = hist_gfcf.drop('MEG61000', axis=1).join(df)
df = pd.concat([hist_gfcf.loc[:, 'IPG61000']] * 3, axis=1)
df.columns = pd.MultiIndex.from_tuples([('IPG61110', 'Elementary and secondary schools'),
('IPG61120', 'Community colleges and C.E.G.E.P.s'),
('IPG61130', 'Universities')])
hist_gfcf = hist_gfcf.drop('IPG61000', axis=1).join(df)
df = hist_gfcf.loc[:, 'COG62200'].copy()
df.columns = pd.MultiIndex.from_tuples(
[('COG62A00', 'Ambulatory health care services and social assistance')])
hist_gfcf = hist_gfcf.join(df)
df = hist_gfcf.loc[:, 'MEG62200'].copy()
df.columns = pd.MultiIndex.from_tuples(
[('MEG62A00', 'Ambulatory health care services and social assistance')])
hist_gfcf = hist_gfcf.join(df)
df = hist_gfcf.loc[:, 'IPG62200'].copy()
df.columns = pd.MultiIndex.from_tuples(
[('IPG62A00', 'Ambulatory health care services and social assistance')])
hist_gfcf = hist_gfcf.join(df)
# differentiate between public and private capitals
hist_gfcf.columns = [(i[0], i[1] + ' (private)') if re.search(r'^COB61|^MEB61|^IPB61|^MEBU', i[0])
else i for i in hist_gfcf.columns]
hist_gfcf.columns = [(i[0], i[1] + ' (public)') if re.search(r'^COG61|^MEG61|^IPG61|^MEGU', i[0])
else i for i in hist_gfcf.columns]
hist_gfcf.columns = [(i[0], i[1] + ' (non-profit)') if re.search(r'^MENU', i[0])
else i for i in hist_gfcf.columns]
hist_gfcf.columns = pd.MultiIndex.from_tuples([i for i in hist_gfcf.columns])
hist_gfcf_public = hist_gfcf.loc[:, [i for i in hist_gfcf.columns if (re.findall(r'^COG', i[0]) or
re.findall(r'^MEG', i[0]) or
re.findall(r'^IPG', i[0]) or
re.findall(r'^CON', i[0]) or
re.findall(r'^MEN', i[0]) or
re.findall(r'^IPN', i[0]))]]
hist_gfcf_private = hist_gfcf.loc[:, [i for i in hist_gfcf.columns if not (re.findall(r'^COG', i[0]) or
re.findall(r'^MEG', i[0]) or
re.findall(r'^IPG', i[0]) or
re.findall(r'^CON', i[0]) or
re.findall(r'^MEN', i[0]) or
re.findall(r'^IPN', i[0]))]]
# load total provincial consumption of fixed capital data from StatCan
factor_prod = pd.read_csv(pkg_resources.resource_stream(
__name__, '/Data/Capitals_endogenization/factor_of_production_detail_StatCan.csv'))
# rename to match with names of embassies in supply and use tables
factor_prod.loc[factor_prod.GEO == 'Outside Canada', 'GEO'] = 'Canadian territorial enclaves abroad'
factor_prod = factor_prod[
(factor_prod.REF_DATE == self.year) & (factor_prod.GEO.isin(list(self.matching_dict.values())))]
# load mapping connecting IOCC (intermediary sectors) to GFCF categories
if self.year in [2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]:
endo = pd.read_excel(pkg_resources.resource_stream(__name__, '/Data/Concordances/2014-2021/Endogenizing.xlsx'))
elif self.year in [2022]:
endo = pd.read_excel(
pkg_resources.resource_stream(__name__, '/Data/Concordances/2022/Endogenizing.xlsx'))
self.K = pd.DataFrame(0, self.U.index, self.U.columns, float)
self.W = pd.concat([self.W, pd.DataFrame(0, index=[(i, 'Net mixed income') for i in self.matching_dict.keys()] +
[(i, 'Net operating surplus') for i in self.matching_dict.keys()],
columns=self.W.columns)])
# get capitals matrix
for province in self.matching_dict.keys():
gfcf_public = self.Y.loc(axis=1)[province, ['Gross fixed capital formation, Construction',
'Gross fixed capital formation, Machinery and equipment',
'Gross fixed capital formation, Intellectual property products'],
list(set([i[1] for i in hist_gfcf_public.columns]))].groupby(axis=1, level=[0, 2]).sum().copy()
gfcf_private = self.Y.loc(axis=1)[province, ['Gross fixed capital formation, Construction',
'Gross fixed capital formation, Machinery and equipment',
'Gross fixed capital formation, Intellectual property products'],
list(set([i[1] for i in hist_gfcf_private.columns]))].groupby(axis=1, level=[0, 2]).sum().copy()
gfcf_public = gfcf_public.drop(
[i for i in gfcf_public.columns if 'Used cars and equipment and scrap' in i[1]], axis=1)
gfcf_private = gfcf_private.drop(
[i for i in gfcf_private.columns if 'Used cars and equipment and scrap' in i[1]], axis=1)
cfc_public = (hist_gfcf_public.loc[province].mean() /
hist_gfcf_public.loc[province].mean().sum() *
factor_prod.loc[
(factor_prod.GEO == self.matching_dict[province]) &
(factor_prod.Estimates == 'Consumption of fixed capital: general governments and non-profit institutions serving households'),
'VALUE'].iloc[0] * 1000000).fillna(0)
cfc_private_corpo = (hist_gfcf_private.loc[province].mean() /
hist_gfcf_private.loc[province].mean().sum() *
factor_prod.loc[(factor_prod.GEO == self.matching_dict[province]) &
(factor_prod.Estimates == 'Consumption of fixed capital: corporations'),
'VALUE'].sum() * 1000000).fillna(0)
cfc_private_not_corpo = (hist_gfcf_private.loc[province].mean() /
hist_gfcf_private.loc[province].mean().sum() *
factor_prod.loc[(factor_prod.GEO == self.matching_dict[province]) &
(factor_prod.Estimates == 'Consumption of fixed capital: unincorporated businesses'),
'VALUE'].sum() * 1000000).fillna(0)
cfc_public.index = [i[1] for i in cfc_public.index]
cfc_public = cfc_public.groupby(cfc_public.index).sum()
cfc_private_corpo.index = [i[1] for i in cfc_private_corpo.index]
cfc_private_corpo = cfc_private_corpo.groupby(cfc_private_corpo.index).sum()
cfc_private_not_corpo.index = [i[1] for i in cfc_private_not_corpo.index]
cfc_private_not_corpo = cfc_private_not_corpo.groupby(cfc_private_not_corpo.index).sum()
# rescale because of historical investments that are not present in year of study
cfc_public = (cfc_public.loc[
[i for i in cfc_public.index if gfcf_public.sum().loc(axis=0)[province, i] != 0]] /
cfc_public.loc[[i for i in cfc_public.index if
gfcf_public.sum().loc(axis=0)[province, i] != 0]].sum() * cfc_public.sum())
cfc_public_rescaled = ((gfcf_public.loc[:, province] / gfcf_public.loc[:, province].sum()).fillna(0) *
cfc_public.reindex([i[1] for i in gfcf_public.columns]).fillna(0))
cfc_private_corpo = (cfc_private_corpo.loc[[i for i in cfc_private_corpo.index if
gfcf_private.sum().loc(axis=0)[province, i] != 0]] /
cfc_private_corpo.loc[[i for i in cfc_private_corpo.index if
gfcf_private.sum().loc(axis=0)[province, i] != 0]].sum() *
cfc_private_corpo.sum())
cfc_private_corpo_rescaled = (
(gfcf_private.loc[:, province] / gfcf_private.loc[:, province].sum()).fillna(0) *
cfc_private_corpo.reindex([i[1] for i in gfcf_private.columns]).fillna(0))
cfc_private_not_corpo = (
cfc_private_not_corpo.loc[
[i for i in cfc_private_not_corpo.index if gfcf_private.sum().loc(axis=0)[province, i] != 0]] /
cfc_private_not_corpo.loc[[i for i in cfc_private_not_corpo.index if
gfcf_private.sum().loc(axis=0)[province, i] != 0]].sum() *
cfc_private_not_corpo.sum())
cfc_private_not_corpo_rescaled = (
(gfcf_private.loc[:, province] / gfcf_private.loc[:, province].sum()).fillna(0) *
cfc_private_not_corpo.reindex([i[1] for i in gfcf_private.columns]).fillna(0))
# ensure rescaling works correctly
assert np.isclose(
cfc_public_rescaled.sum().sum() + cfc_private_corpo_rescaled.sum().sum() + cfc_private_not_corpo_rescaled.sum().sum(),
factor_prod.loc[(factor_prod.GEO == self.matching_dict[province]) & (
factor_prod.Estimates.isin(['Consumption of fixed capital: corporations',
'Consumption of fixed capital: unincorporated businesses',
'Consumption of fixed capital: general governments and non-profit institutions serving households'])),
'VALUE'].sum().sum() * 1000000)
cfc_rescaled = pd.concat([cfc_public_rescaled, cfc_private_corpo_rescaled, cfc_private_not_corpo_rescaled],
axis=1)
cfc_rescaled = cfc_rescaled.groupby(axis=1, level=0).sum()
for capital in cfc_rescaled.columns:
# total K and total factor_prod don't match because IF condition not respected all the time
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())
assert np.isclose(share.sum(), 1)
for sector in share.index:
# add to capital matrix
self.K.loc[:, (province, sector)] += (cfc_rescaled.loc[:, capital] * share.loc[sector])
# remove from value-added matrix
if capital in cfc_private_not_corpo_rescaled.columns.tolist():
self.W.loc[(province, 'Net mixed income'), (province, sector)] += (
self.W.loc[(province, 'Gross mixed income'), (province, sector)] -
(cfc_private_not_corpo_rescaled.loc[:, capital] * share.loc[sector]).sum()
)
self.W.loc[(province, 'Net operating surplus'), (province, sector)] += (
self.W.loc[(province, 'Gross operating surplus'), (province, sector)] -
(pd.concat([cfc_private_corpo_rescaled, cfc_public_rescaled], axis=1).loc[:, capital] *
share.loc[sector]).sum()
)
# Gotta change Gross indicators for net ones for the residential building construction sector
self.W.loc[[i for i in self.W.index if i[1] == 'Net mixed income'],
[j for j in self.W.columns if j[1] == 'Residential building construction']] = (
self.W.loc(axis=1)[:, 'Residential building construction'].loc(axis=0)[:, 'Gross mixed income'].values)
self.W.loc[[i for i in self.W.index if i[1] == 'Net operating surplus'],
[j for j in self.W.columns if j[1] == 'Residential building construction']] = (
self.W.loc(axis=1)[:, 'Residential building construction'].loc(axis=0)[:, 'Gross operating surplus'].values)
self.W = self.W.drop(['Gross operating surplus', 'Gross mixed income'], axis=0, level=1)
# check balance still respected
assert np.isclose((self.U.sum() + self.W.sum() + self.K.sum()), self.g.sum()).all()
# move Used cars and equipment and scrap categories to changes in inventories
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)
# drop the share of the GFCF that was endogenized, the redisual represents investments of that year
# first we need to retranslate the endogenized capitals (i.e., go back to the COICOP classification)
endogenized_capitals = self.K.copy()
endogenized_capitals.columns = pd.MultiIndex.from_tuples(
[(i[0], endo.set_index('IOIC').drop('IOIC code', axis=1).loc[i[1], 'Capitals']) if
i[1] != 'Residential building construction' else i for i in self.K.columns])
endogenized_capitals = endogenized_capitals.groupby(endogenized_capitals.columns, axis=1).sum()
endogenized_capitals.columns = pd.MultiIndex.from_tuples(endogenized_capitals.columns)
# isolate and format construction capitals
buildings = list(set([i[1] for i in self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Construction'].sum(1)[
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Construction'].sum(1) != 0
].index.tolist()]))
buildings = endogenized_capitals.loc(axis=0)[:, buildings].reindex(self.Y.index).fillna(0)
buildings.columns = pd.MultiIndex.from_tuples(
[(i[0], 'Gross fixed capital formation, Construction', i[1]) for i in buildings.columns])
# isolate and format machinery and equipment capitals
machines = list(
set([i[1] for i in self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Machinery and equipment'].sum(1)[
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Machinery and equipment'].sum(1) != 0
].index.tolist()]))
machines = endogenized_capitals.loc(axis=0)[:, machines].reindex(self.Y.index).fillna(0)
machines.columns = pd.MultiIndex.from_tuples(
[(i[0], 'Gross fixed capital formation, Machinery and equipment', i[1]) for i in machines.columns])
# isolate and format IP capitals
ip = list(set([i[1] for i in
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Intellectual property products'].sum(1)[
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Intellectual property products'].sum(
1) != 0
].index.tolist()]))
ip = endogenized_capitals.loc(axis=0)[:, ip].reindex(self.Y.index).fillna(0)
ip.columns = pd.MultiIndex.from_tuples(
[(i[0], 'Gross fixed capital formation, Intellectual property products', i[1]) for i in ip.columns])
# do the actual removing
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Construction'] -= buildings
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Machinery and equipment'] -= machines
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Intellectual property products'] -= ip
# remove negative values, they clearly do not represent an investment of this year
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Construction'] = (
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Construction'][
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Construction'] > 0
]
).fillna(0)
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Machinery and equipment'] = (
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Machinery and equipment'][
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Machinery and equipment'] > 0
]
).fillna(0)
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Intellectual property products'] = (
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Intellectual property products'][
self.Y.loc(axis=1)[:, 'Gross fixed capital formation, Intellectual property products'] > 0
]
).fillna(0)
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
df = self.K[self.K < -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.K.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()