Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

initial agent based economic model [do not merge] #19

Open
wants to merge 3 commits into
base: staging
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/disease_model/models/compartment_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,10 @@ def predict_with_params(
population_data, past_health_data, params)

prediction = integrate.solve_ivp(
self.differential_equations,
fun=lambda t, y: self.differential_equations(t, y, tuple(self.parameter_config.flatten(params))),
t_span=(0, forecast_length),
t_eval=np.arange(1, forecast_length + 1),
y0=initial_state,
args=self.parameter_config.flatten(params))
y0=initial_state)

return self.format_output(prediction.y)

Expand Down
2 changes: 1 addition & 1 deletion src/disease_model/models/seir.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def differential_equations(
# pylint: disable=invalid-name,too-many-locals
s, e, i, r, _ = compartments
population = s + e + i + r
parameters = self.parameter_config.parse(args)
parameters = self.parameter_config.parse(args[0])
beta = parameters['beta']
gamma = parameters['gamma']
sigma = parameters['sigma']
Expand Down
43 changes: 43 additions & 0 deletions src/economic_model/data/india_input.csv

Large diffs are not rendered by default.

50 changes: 25 additions & 25 deletions src/economic_model/data/sector_mapping.csv
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
lockdown_sector,sector
agriculture,
chemical,Manufacturing
commerce,"Trade, Hotels, Transport, Communication and Services Related to Broadcasting"
construction,Construction
education,Other services
fin_prof_services,"Financial, Real Estate and Professional Services"
food_consumables,
healthcare,Other services
hospitality_tourism,"Trade, Hotels, Transport, Communication and Services Related to Broadcasting"
manufacturing,Manufacturing
mining,Mining and quarrying
media,Other services
energy,"Electricity, gas, water supply & other utility services"
telecom,"Transport, storage, communication & services related to broadcasting"
public_admin,"Public Administration Defence, and Other Services"
supply_chain_ship,"Transport, storage, communication & services related to broadcasting"
forest_husb_fish,
textiles,"Trade, Hotels, Transport, Communication and Services Related to Broadcasting"
transportation ,"Transport, storage, communication & services related to broadcasting"
utilities,"Electricity, gas, water supply & other utility services"
open_border,"Transport, storage, communication & services related to broadcasting"
air_travel,"Transport, storage, communication & services related to broadcasting"
roal_rail_travel,"Transport, storage, communication & services related to broadcasting"
public_transport,"Transport, storage, communication & services related to broadcasting"
lockdown_sector,sector,id
agriculture,"TTL_01T03: Agriculture, forestry and fishing",0
chemical,TTL_20T21: Chemicals and pharmaceutical products,9
commerce,TTL_69T82: Other business sector services,30
construction,TTL_41T43: Construction,21
education,TTL_85: Education,32
fin_prof_services,TTL_64T66: Financial and insurance activities,28
food_consumables,"TTL_10T12: Food products, beverages and tobacco",4
healthcare,TTL_86T88: Human health and social work,33
hospitality_tourism,"TTL_90T96: Arts, entertainment, recreation and other service activities",34
manufacturing,TTL_24: Manufacture of basic metals,12
mining,TTL_05T06: Mining and extraction of energy producing products,1
media,"TTL_58T60: Publishing, audiovisual and broadcasting activities",25
energy,TTL_05T06: Mining and extraction of energy producing products,1
telecom,TTL_61: Telecommunications,26
public_admin,TTL_84: Public administration and defence,31
supply_chain_ship,TTL_49T53: Transportation and storage,23
forest_husb_fish,"TTL_01T03: Agriculture, forestry and fishing",0
textiles,"TTL_13T15: Textiles, wearing apparel, leather and related products",5
transportation ,TTL_49T53: Transportation and storage,23
utilities,"TTL_35T39: Electricity, gas, water supply, sewerage, waste and remediation services",20
open_border,TTL_49T53: Transportation and storage,23
air_travel,TTL_49T53: Transportation and storage,23
roal_rail_travel,TTL_49T53: Transportation and storage,23
public_transport,TTL_49T53: Transportation and storage,23
Empty file.
28 changes: 22 additions & 6 deletions src/economic_model/models/basic_lockdown_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
"""
from typing import Dict
import attr
import os
import numpy as np
import pandas as pd
from help_project.src.economic_model.utils import gva_data
from help_project.src.exitstrategies import lockdown_policy as lockdown
from help_project.src.economic_model.models.economy_simulation import simulate_economy


class EconomicLockdownModel():
Expand Down Expand Up @@ -33,19 +36,32 @@ def _get_economic_vector_for_single_policy(self, lockdown_policy: lockdown.Lockd
sector_mappings.iloc[i]['lockdown_sector'])

baseline_gva = gva.get_gvas()
adjusted_gva = {}
india_input_output = pd.read_csv(os.path.dirname(__file__) + '/../data/india_input.csv')
india_input_output.columns = india_input_output.iloc[0]
india_input_output = india_input_output.iloc[1:]
india_input_output = india_input_output.set_index('To: (sector in column)')
india_input_output = india_input_output.drop(
['TXS_IMP_FNL: Taxes less subsidies on intermediate and final products (paid in foreign countries)',
'TXS_INT_FNL: Taxes less subsidies on intermediate and final products (paid in domestic agencies, includes duty on imported products)',
'TTL_INT_FNL: Total intermediate consumption at purchasers’ prices',
'TTL_97T98: Private households with employed persons'], axis=0)
india_input_output = india_input_output.drop(columns=india_input_output.columns[-8:])
india_input_output = india_input_output.drop(columns=[india_input_output.columns[-2]])
sectors = india_input_output.index.values[:-2]
labor_shocks = {}
for sector in sectors:
labor_shocks[sector]=1
for key in mapping_dict:
if key not in baseline_gva:
if key not in sectors:
continue
weights = []
for sector in mapping_dict[key]:
if sector in lockdown_policy:
weights.append(lockdown_policy[sector])
if len(weights) > 0:
adjusted_gva[key] = baseline_gva[key] * np.mean(weights)
else:
adjusted_gva[key] = baseline_gva[key]
return adjusted_gva
labor_shocks[key] = np.mean(weights)
adjusted_gvas = simulate_economy(labor_shocks)
return adjusted_gvas

def get_economic_vector(
self, lockdown_policy: lockdown.LockdownTimeSeries) -> Dict[str, float]:
Expand Down
138 changes: 138 additions & 0 deletions src/economic_model/models/economy_simulation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
from __future__ import division # makes division work correctly
import random
from builtins import range
from help_project.src.economic_model.models.firm import Firm
from help_project.src.economic_model.models.household import Household
from abcEconomics import Simulation
import pandas as pd
import numpy as np
import sys,os
"""
1. declares the timeline
2. build one Household agent representing all the households and one Firm each for each sector
3. For every labor_endowment an agent has gets one trade or usable labor per round. If it is not used at the end of the round it disaapears.
4. Firms' and Households' possesions are monitored ot the points marked in timeline.
"""

# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
sys.stdout = sys.__stdout__

# blockPrint()
def main(parameters, agent_parameters, labor_alphas, shocks_to_labor_supply):
simulation = Simulation(processes=1)

firms = simulation.build_agents(
Firm, 'firm', num_sectors = len(agent_parameters), agent_parameters=agent_parameters)
households = simulation.build_agents(
Household, 'household', number=1, firms_info=agent_parameters, labor_alphas = labor_alphas[0], needed_labor = labor_alphas[1])


for rnd in range(parameters['rounds']):
if rnd>5:
# for i in range(number_sectors):
# enablePrint()
# print(firms[i].last_output)
# blockPrint()
households.apply_shocks(shocks_to_labor_supply)
simulation.advance_round(rnd)
households.create_labor()
households.sell_labor()
firms.buy_labor()
firms.production()
firms.panel_log(goods=['money', 'GOOD_sector1', 'GOOD_sector2'],
variables=['last_output'])
firms.quotes()
households.buy_goods()
firms.buy_goods()
firms.sell_goods()
households.panel_log(goods=['money', 'GOOD_sector1', 'GOOD_sector2'],
variables=['current_utility'])
households.consumption()
firms.adjust_target()
# firms.adjust_price()
simulation.finalize()
firms = pd.read_csv(simulation.path +'/panel_firm.csv')
shocks = []
for i in range(len(agent_parameters)):
temp_firms = firms.loc[firms['name']=='firm'+str(i)]
shocks.append(temp_firms['last_output'].iloc[-1]/temp_firms['last_output'].iloc[0])
return shocks

def comma_convert(stri):
return float(stri.replace(",", ""))

def series_convert(series):
return series.apply(comma_convert)

def series_normalize(series):
return (series / np.sum(series.iloc[:-1]))


def simulate_economy(shocks_to_labor_supply=None):
parameters = {'name': '2x2',
'random_seed': None,
'rounds': 500,}

# Cleaning input output table for india
india_input_output = pd.read_csv(os.path.dirname(__file__) + '/../data/india_input.csv')
india_input_output.columns = india_input_output.iloc[0]
india_input_output = india_input_output.iloc[1:]
india_input_output = india_input_output.set_index('To: (sector in column)')
india_input_output = india_input_output.apply(series_convert)
india_input_output.iloc[-2] = india_input_output.iloc[-2] + india_input_output.iloc[-4] + india_input_output.iloc[-5] +india_input_output.iloc[-6]
india_input_output = india_input_output.drop(['TXS_IMP_FNL: Taxes less subsidies on intermediate and final products (paid in foreign countries)' , 'TXS_INT_FNL: Taxes less subsidies on intermediate and final products (paid in domestic agencies, includes duty on imported products)', 'TTL_INT_FNL: Total intermediate consumption at purchasers’ prices', 'TTL_97T98: Private households with employed persons'], axis = 0)
india_input_output = india_input_output.drop(columns = india_input_output.columns[-8:])
india_input_output = india_input_output.drop(columns = [india_input_output.columns[-2]])

number_sectors = len(india_input_output)-2
ratio_df = india_input_output.iloc[:,:-1].apply(series_normalize)
labor_df = india_input_output.iloc[:-2,-1]/np.sum(india_input_output.iloc[:-2,-1])

agent_parameters = []
labor_dict = {}
labor_requirement = 0
for i in range(number_sectors):
temp_dict = {}
temp_dict['sector'] = 'sector'+str(i)
ratio_dict = {}
for j in range(number_sectors):
if ratio_df.iloc[j,i] > 0.00001:
ratio_dict['GOOD_sector'+str(j)] = ratio_df.iloc[j,i]
ratio_dict['labor'] = ratio_df.iloc[number_sectors,i]
temp_dict['ratio_dict'] = ratio_dict
agent_parameters.append(temp_dict)
labor_dict['GOOD_sector'+str(i)] = labor_df.iloc[i]

output_input_ratio = [0]*number_sectors
for i in range(number_sectors):
for key in agent_parameters[i]['ratio_dict'].keys():
if key=="labor":
labor_requirement+=agent_parameters[i]['ratio_dict'][key]
continue
output_input_ratio[int(key.split('r')[-1])] += agent_parameters[i]['ratio_dict'][key]

for key in labor_dict.keys():
output_input_ratio[int(key.split('r')[-1])] += labor_dict[key]
labor_alphas = [labor_dict, labor_requirement]
for i in range(number_sectors):
agent_parameters[i]['output_input_ratio']=output_input_ratio[i]
shocks_array=[]
for i in range(len(india_input_output)-2):
if india_input_output.index[i] in shocks_to_labor_supply.keys():
shocks_array.append(0.5 + 0.5*(shocks_to_labor_supply[india_input_output.index[i]]))
else:
shocks_array.append(1)
shocks_to_labor_supply = shocks_array
if shocks_to_labor_supply is None:
shocks_to_labor_supply = [random.uniform(0.5,1) for i in range(number_sectors)]
shocks = main(parameters,agent_parameters,labor_alphas, shocks_to_labor_supply)
GVAs={}
for i in range(number_sectors):
GVAs[india_input_output.index[i]]=(shocks[i]*india_input_output.iloc[-1,i])
return GVAs

Loading