formatting
This commit is contained in:
parent
a8d50e1f81
commit
5b0e17ce52
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -51,19 +51,22 @@ class ControllerDB:
|
||||||
# break
|
# break
|
||||||
# break
|
# break
|
||||||
# list_dct = [{'140': ['1.4.5.1']}]
|
# list_dct = [{'140': ['1.4.5.1']}]
|
||||||
|
list_dct = [{'133': ['1.4.4.1']}]
|
||||||
|
# list_dct = [{'2': ['1.1.3']}]
|
||||||
|
# list_dct = [{'135': ['1.3.2.1']}]
|
||||||
for idx_exp, dct in enumerate(list_dct):
|
for idx_exp, dct in enumerate(list_dct):
|
||||||
self.add_experiment_1(idx_exp, self.dct_parameter['n_max_trial'],
|
self.add_experiment_1(idx_exp, self.dct_parameter['n_max_trial'],
|
||||||
dct)
|
dct)
|
||||||
print(f'Inserted experiment for exp {idx_exp}!')
|
print(f'Inserted experiment for exp {idx_exp}!')
|
||||||
|
|
||||||
def add_experiment_1(self, idx_exp, n_max_trial,
|
def add_experiment_1(self, idx_exp, n_max_trial,
|
||||||
dct_list_init_remove_firm_prod):
|
dct_lst_init_remove_firm_prod):
|
||||||
e = Experiment(
|
e = Experiment(
|
||||||
idx_exp=idx_exp,
|
idx_exp=idx_exp,
|
||||||
n_sample=int(self.dct_parameter['n_sample']),
|
n_sample=int(self.dct_parameter['n_sample']),
|
||||||
n_iter=int(self.dct_parameter['n_iter']),
|
n_iter=int(self.dct_parameter['n_iter']),
|
||||||
n_max_trial=n_max_trial,
|
n_max_trial=n_max_trial,
|
||||||
dct_list_init_remove_firm_prod=dct_list_init_remove_firm_prod)
|
dct_lst_init_remove_firm_prod=dct_lst_init_remove_firm_prod)
|
||||||
db_session.add(e)
|
db_session.add(e)
|
||||||
db_session.commit()
|
db_session.commit()
|
||||||
|
|
||||||
|
|
119
firm.py
119
firm.py
|
@ -3,7 +3,7 @@ import math
|
||||||
|
|
||||||
|
|
||||||
class FirmAgent(ap.Agent):
|
class FirmAgent(ap.Agent):
|
||||||
def setup(self, code, name, type_region, revenue_log, a_list_product):
|
def setup(self, code, name, type_region, revenue_log, a_lst_product):
|
||||||
self.firm_network = self.model.firm_network
|
self.firm_network = self.model.firm_network
|
||||||
self.product_network = self.model.product_network
|
self.product_network = self.model.product_network
|
||||||
|
|
||||||
|
@ -11,81 +11,72 @@ class FirmAgent(ap.Agent):
|
||||||
self.name = name
|
self.name = name
|
||||||
self.type_region = type_region
|
self.type_region = type_region
|
||||||
self.revenue_log = revenue_log
|
self.revenue_log = revenue_log
|
||||||
self.a_list_product = a_list_product
|
self.a_lst_product = a_lst_product
|
||||||
self.dct_prod_capacity = dict.fromkeys(self.a_list_product)
|
self.dct_prod_capacity = dict.fromkeys(self.a_lst_product)
|
||||||
|
|
||||||
self.a_list_up_product_removed = ap.AgentList(self.model, [])
|
self.a_lst_up_product_removed = ap.AgentList(self.model, [])
|
||||||
self.a_list_product_disrupted = ap.AgentList(self.model, [])
|
self.a_lst_product_disrupted = ap.AgentList(self.model, [])
|
||||||
self.a_list_product_removed = ap.AgentList(self.model, [])
|
self.a_lst_product_removed = ap.AgentList(self.model, [])
|
||||||
|
|
||||||
self.dct_num_trial_up_product_removed = {}
|
self.dct_n_trial_up_product_removed = {}
|
||||||
self.dct_request_prod_from_firm = {}
|
self.dct_request_prod_from_firm = {}
|
||||||
|
|
||||||
def remove_edge_to_cus_remove_cus_up_prod(self, remove_product):
|
def remove_edge_to_cus_remove_cus_up_prod(self, remove_product):
|
||||||
list_out_edges = list(
|
lst_out_edge = list(
|
||||||
self.firm_network.graph.out_edges(
|
self.firm_network.graph.out_edges(
|
||||||
self.firm_network.positions[self], keys=True, data='Product'))
|
self.firm_network.positions[self], keys=True, data='Product'))
|
||||||
for n1, n2, key, product_code in list_out_edges:
|
for n1, n2, key, product_code in lst_out_edge:
|
||||||
if product_code == remove_product.code:
|
if product_code == remove_product.code:
|
||||||
# remove edge
|
# remove edge
|
||||||
# print(n1, n2, key, product_code)
|
|
||||||
self.firm_network.graph.remove_edge(n1, n2, key)
|
self.firm_network.graph.remove_edge(n1, n2, key)
|
||||||
|
|
||||||
# remove customer up product conditionally
|
# remove customer up product conditionally
|
||||||
customer = ap.AgentIter(self.model, n2).to_list()[0]
|
customer = ap.AgentIter(self.model, n2).to_list()[0]
|
||||||
list_in_edges = list(
|
lst_in_edge = list(
|
||||||
self.firm_network.graph.in_edges(n2,
|
self.firm_network.graph.in_edges(n2,
|
||||||
keys=True,
|
keys=True,
|
||||||
data='Product'))
|
data='Product'))
|
||||||
select_edges = [
|
lst_select_in_edge = [
|
||||||
edge for edge in list_in_edges
|
edge for edge in lst_in_edge
|
||||||
if edge[-1] == remove_product.code
|
if edge[-1] == remove_product.code
|
||||||
]
|
]
|
||||||
# print(select_edges)
|
prod_remove = math.exp(-1 * len(lst_select_in_edge))
|
||||||
p_remove = math.exp(-1 * len(select_edges))
|
if self.model.nprandom.choice([True, False],
|
||||||
if self.model.nprandom.choice([True, False], p=[p_remove, 1-p_remove]):
|
p=[prod_remove,
|
||||||
print(self.name, remove_product.code, 'affect', customer.name)
|
1 - prod_remove]):
|
||||||
|
print(self.name, remove_product.code, 'affect',
|
||||||
|
customer.name)
|
||||||
if remove_product not in \
|
if remove_product not in \
|
||||||
customer.a_list_up_product_removed:
|
customer.a_lst_up_product_removed:
|
||||||
customer.a_list_up_product_removed.append(
|
customer.a_lst_up_product_removed.append(
|
||||||
remove_product)
|
remove_product)
|
||||||
customer.dct_num_trial_up_product_removed[
|
customer.dct_n_trial_up_product_removed[
|
||||||
remove_product] = 0
|
remove_product] = 0
|
||||||
|
|
||||||
# # disrupt customer
|
|
||||||
# customer = ap.AgentIter(self.model, n2).to_list()[0]
|
|
||||||
# for product in customer.a_list_product:
|
|
||||||
# if product in remove_product.a_successors():
|
|
||||||
# if product not in customer.a_list_product_disrupted:
|
|
||||||
# customer.a_list_product_disrupted.append(
|
|
||||||
# product)
|
|
||||||
# print(customer.a_list_product_disrupted.code)
|
|
||||||
|
|
||||||
def seek_alt_supply(self):
|
def seek_alt_supply(self):
|
||||||
for product in self.a_list_up_product_removed:
|
for product in self.a_lst_up_product_removed:
|
||||||
print(f"{self.name} seek alt supply for {product.code}")
|
print(f"{self.name} seek alt supply for {product.code}")
|
||||||
if self.dct_num_trial_up_product_removed[
|
if self.dct_n_trial_up_product_removed[
|
||||||
product] <= self.model.int_n_max_trial:
|
product] <= self.model.int_n_max_trial:
|
||||||
# select a list of candidate firm that has the product
|
# select a list of candidate firm that has the product
|
||||||
candidate_alt_supply = self.model.a_list_total_firms.select([
|
candidate_alt_supply = self.model.a_lst_total_firms.select([
|
||||||
product in firm.a_list_product
|
product in firm.a_lst_product
|
||||||
and product not in firm.a_list_product_removed
|
and product not in firm.a_lst_product_removed
|
||||||
for firm in self.model.a_list_total_firms
|
for firm in self.model.a_lst_total_firms
|
||||||
])
|
])
|
||||||
# print(candidate_alt_supply)
|
|
||||||
# print(candidate_alt_supply.name)
|
|
||||||
# print(candidate_alt_supply.a_list_product.code)
|
|
||||||
if not candidate_alt_supply:
|
if not candidate_alt_supply:
|
||||||
continue
|
continue
|
||||||
# select based on size
|
# select based on size
|
||||||
list_prob = [
|
lst_prob = [
|
||||||
size / sum(candidate_alt_supply.revenue_log)
|
size / sum(candidate_alt_supply.revenue_log)
|
||||||
for size in candidate_alt_supply.revenue_log
|
for size in candidate_alt_supply.revenue_log
|
||||||
]
|
]
|
||||||
select_alt_supply = self.model.nprandom.choice(
|
select_alt_supply = self.model.nprandom.choice(
|
||||||
candidate_alt_supply, p=list_prob)
|
candidate_alt_supply, p=lst_prob)
|
||||||
print(f"{self.name} selct alt supply for {product.code} from {select_alt_supply.name}")
|
print(
|
||||||
assert product in select_alt_supply.a_list_product, \
|
f"{self.name} selct alt supply for {product.code} from {select_alt_supply.name}"
|
||||||
|
)
|
||||||
|
assert product in select_alt_supply.a_lst_product, \
|
||||||
f"{select_alt_supply} \
|
f"{select_alt_supply} \
|
||||||
does not produce requested product {product}"
|
does not produce requested product {product}"
|
||||||
|
|
||||||
|
@ -104,32 +95,36 @@ class FirmAgent(ap.Agent):
|
||||||
select_alt_supply.dct_request_prod_from_firm.items()
|
select_alt_supply.dct_request_prod_from_firm.items()
|
||||||
})
|
})
|
||||||
|
|
||||||
self.dct_num_trial_up_product_removed[product] += 1
|
self.dct_n_trial_up_product_removed[product] += 1
|
||||||
|
|
||||||
def handle_request(self):
|
def handle_request(self):
|
||||||
print(self.name, 'handle_request')
|
print(self.name, 'handle_request')
|
||||||
for product, list_firm in self.dct_request_prod_from_firm.items():
|
for product, lst_firm in self.dct_request_prod_from_firm.items():
|
||||||
if self.dct_prod_capacity[product] > 0:
|
if self.dct_prod_capacity[product] > 0:
|
||||||
if len(list_firm) == 0:
|
if len(lst_firm) == 0:
|
||||||
continue
|
continue
|
||||||
elif len(list_firm) == 1:
|
elif len(lst_firm) == 1:
|
||||||
self.accept_request(list_firm[0], product)
|
self.accept_request(lst_firm[0], product)
|
||||||
elif len(list_firm) > 1:
|
elif len(lst_firm) > 1:
|
||||||
# handling based on connection
|
# handling based on connection
|
||||||
# TBC
|
# TBC
|
||||||
# handling based on size
|
# handling based on size
|
||||||
list_size = [firm.revenue_log for firm in list_firm]
|
lst_firm_size = [firm.revenue_log for firm in lst_firm]
|
||||||
list_prob = [size / sum(list_size) for size in list_size]
|
lst_prob = [
|
||||||
select_customer = self.model.nprandom.choice(list_firm,
|
size / sum(lst_firm_size) for size in lst_firm_size
|
||||||
p=list_prob)
|
]
|
||||||
|
select_customer = self.model.nprandom.choice(lst_firm,
|
||||||
|
p=lst_prob)
|
||||||
self.accept_request(select_customer, product)
|
self.accept_request(select_customer, product)
|
||||||
# print(product.code, [firm.name for firm in list_firm])
|
|
||||||
|
|
||||||
def accept_request(self, down_firm, product):
|
def accept_request(self, down_firm, product):
|
||||||
# if self.model.nprandom.choice([True, False], p=[0.1, 0.9]):
|
lst_firm_size = [
|
||||||
lst_f_s = [firm.revenue_log for firm in self.model.a_list_total_firms if product in firm.a_list_product]
|
firm.revenue_log for firm in self.model.a_lst_total_firms
|
||||||
p_accept = self.revenue_log / sum(lst_f_s)
|
if product in firm.a_lst_product
|
||||||
if self.model.nprandom.choice([True, False], p=[p_accept, 1-p_accept]):
|
]
|
||||||
|
prod_accept = self.revenue_log / sum(lst_firm_size)
|
||||||
|
if self.model.nprandom.choice([True, False],
|
||||||
|
p=[prod_accept, 1 - prod_accept]):
|
||||||
self.firm_network.graph.add_edges_from([
|
self.firm_network.graph.add_edges_from([
|
||||||
(self.firm_network.positions[self],
|
(self.firm_network.positions[self],
|
||||||
self.firm_network.positions[down_firm], {
|
self.firm_network.positions[down_firm], {
|
||||||
|
@ -138,12 +133,14 @@ class FirmAgent(ap.Agent):
|
||||||
])
|
])
|
||||||
self.dct_prod_capacity[product] -= 1
|
self.dct_prod_capacity[product] -= 1
|
||||||
self.dct_request_prod_from_firm[product].remove(down_firm)
|
self.dct_request_prod_from_firm[product].remove(down_firm)
|
||||||
down_firm.a_list_up_product_removed.remove(product)
|
down_firm.a_lst_up_product_removed.remove(product)
|
||||||
print(f"{self.name} accept {product.code} request from {down_firm.name}")
|
print(
|
||||||
|
f"{self.name} accept {product.code} request from {down_firm.name}"
|
||||||
|
)
|
||||||
|
|
||||||
def clean_before_trial(self):
|
def clean_before_trial(self):
|
||||||
self.dct_request_prod_from_firm = {}
|
self.dct_request_prod_from_firm = {}
|
||||||
|
|
||||||
def clean_before_time_step(self):
|
def clean_before_time_step(self):
|
||||||
self.dct_num_trial_up_product_removed = {}
|
self.dct_n_trial_up_product_removed = {}
|
||||||
self.a_list_up_product_removed = ap.AgentList(self.model, [])
|
self.a_lst_up_product_removed = ap.AgentList(self.model, [])
|
||||||
|
|
309
model.py
309
model.py
|
@ -5,33 +5,9 @@ import random
|
||||||
import networkx as nx
|
import networkx as nx
|
||||||
from firm import FirmAgent
|
from firm import FirmAgent
|
||||||
from product import ProductAgent
|
from product import ProductAgent
|
||||||
from orm import db_session, Sample, Result
|
from orm import db_session, Result
|
||||||
import platform
|
import platform
|
||||||
|
|
||||||
sample = 0
|
|
||||||
seed = 0
|
|
||||||
n_iter = 10
|
|
||||||
# dct_list_init_remove_firm_prod = {133: ['1.4.4.1'], 2: ['1.1.3']}
|
|
||||||
# dct_list_init_remove_firm_prod = {
|
|
||||||
# 135: ['1.3.2.1'],
|
|
||||||
# 133: ['1.4.4.1'],
|
|
||||||
# 2: ['1.1.3']
|
|
||||||
# }
|
|
||||||
dct_list_init_remove_firm_prod = {
|
|
||||||
'140': ['1.4.5.1'],
|
|
||||||
'135': ['1.3.2.1'],
|
|
||||||
'133': ['1.4.4.1'],
|
|
||||||
'2': ['1.1.3']
|
|
||||||
}
|
|
||||||
n_max_trial = 5
|
|
||||||
dct_sample_para = {
|
|
||||||
'sample': sample,
|
|
||||||
'seed': seed,
|
|
||||||
'n_iter': n_iter,
|
|
||||||
'n_max_trial': n_max_trial,
|
|
||||||
'dct_list_init_remove_firm_prod': dct_list_init_remove_firm_prod,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class Model(ap.Model):
|
class Model(ap.Model):
|
||||||
def setup(self):
|
def setup(self):
|
||||||
|
@ -41,7 +17,7 @@ class Model(ap.Model):
|
||||||
self.nprandom = np.random.default_rng(self.p.seed)
|
self.nprandom = np.random.default_rng(self.p.seed)
|
||||||
self.int_n_iter = int(self.p.n_iter)
|
self.int_n_iter = int(self.p.n_iter)
|
||||||
self.int_n_max_trial = int(self.p.n_max_trial)
|
self.int_n_max_trial = int(self.p.n_max_trial)
|
||||||
self.dct_list_remove_firm_prod = self.p.dct_list_init_remove_firm_prod
|
self.dct_lst_remove_firm_prod = self.p.dct_lst_init_remove_firm_prod
|
||||||
|
|
||||||
# init graph bom
|
# init graph bom
|
||||||
BomNodes = pd.read_csv('BomNodes.csv', index_col=0)
|
BomNodes = pd.read_csv('BomNodes.csv', index_col=0)
|
||||||
|
@ -77,68 +53,51 @@ class Model(ap.Model):
|
||||||
|
|
||||||
# add edge to G_firm according to G_bom
|
# add edge to G_firm according to G_bom
|
||||||
for node in nx.nodes(G_Firm):
|
for node in nx.nodes(G_Firm):
|
||||||
# print(node, '-' * 20)
|
|
||||||
for product_code in G_Firm.nodes[node]['Product_Code']:
|
for product_code in G_Firm.nodes[node]['Product_Code']:
|
||||||
# print(product_code)
|
|
||||||
for succ_product_code in list(G_bom.successors(product_code)):
|
for succ_product_code in list(G_bom.successors(product_code)):
|
||||||
# print(succ_product_code)
|
# for each product of a certain firm
|
||||||
list_succ_firms = Firm['Code'][Firm[succ_product_code] ==
|
# get each successor (finished product) of this product
|
||||||
|
# get a list of firm producing this successor
|
||||||
|
lst_succ_firm = Firm['Code'][Firm[succ_product_code] ==
|
||||||
1].to_list()
|
1].to_list()
|
||||||
list_revenue_log = [
|
lst_succ_firm_size = [
|
||||||
G_Firm.nodes[succ_firm]['Revenue_Log']
|
G_Firm.nodes[succ_firm]['Revenue_Log']
|
||||||
for succ_firm in list_succ_firms
|
for succ_firm in lst_succ_firm
|
||||||
]
|
]
|
||||||
# list_prob = [
|
lst_prob = [
|
||||||
# (v - min(list_revenue_log) + 1) /
|
size / sum(lst_succ_firm_size)
|
||||||
# (max(list_revenue_log) - min(list_revenue_log) + 1)
|
for size in lst_succ_firm_size
|
||||||
# for v in list_revenue_log
|
|
||||||
# ]
|
|
||||||
# list_flag = [
|
|
||||||
# self.nprandom.choice([1, 0], p=[prob, 1 - prob])
|
|
||||||
# for prob in list_prob
|
|
||||||
# ]
|
|
||||||
# # print(list(zip(list_succ_firms,list_flag,list_prob)))
|
|
||||||
# list_added_edges = [(node, succ_firm, {
|
|
||||||
# 'Product': product_code
|
|
||||||
# }) for succ_firm, flag in zip(list_succ_firms, list_flag)
|
|
||||||
# if flag == 1]
|
|
||||||
list_prob = [
|
|
||||||
size / sum(list_revenue_log)
|
|
||||||
for size in list_revenue_log
|
|
||||||
]
|
]
|
||||||
list_f_same_p = Firm['Code'][Firm[product_code] ==
|
# select multiple successors based on relative size of this firm
|
||||||
|
lst_same_prod_firm = Firm['Code'][Firm[product_code] ==
|
||||||
1].to_list()
|
1].to_list()
|
||||||
list_f_size_same_p = [
|
lst_same_prod_firm_size = [
|
||||||
G_Firm.nodes[f]['Revenue_Log']
|
G_Firm.nodes[f]['Revenue_Log']
|
||||||
for f in list_f_same_p
|
for f in lst_same_prod_firm
|
||||||
]
|
]
|
||||||
share = G_Firm.nodes[node]['Revenue_Log'] / sum(list_f_size_same_p)
|
share = G_Firm.nodes[node]['Revenue_Log'] / sum(
|
||||||
num_succ_f = round(share * len(list_succ_firms)) if round(share * len(list_succ_firms)) > 0 else 1
|
lst_same_prod_firm_size)
|
||||||
list_choose_firm = self.nprandom.choice(list_succ_firms, num_succ_f,
|
n_succ_firm = round(share * len(lst_succ_firm)) if round(
|
||||||
p=list_prob)
|
share * len(lst_succ_firm)) > 0 else 1 # at least one
|
||||||
list_choose_firm = list(set(list_choose_firm))
|
lst_choose_firm = self.nprandom.choice(lst_succ_firm,
|
||||||
list_added_edges = [(node, succ_firm, {
|
n_succ_firm,
|
||||||
|
p=lst_prob)
|
||||||
|
lst_choose_firm = list(
|
||||||
|
set(lst_choose_firm
|
||||||
|
)) # nprandom.choice may have duplicates
|
||||||
|
lst_add_edge = [(node, succ_firm, {
|
||||||
'Product': product_code
|
'Product': product_code
|
||||||
}) for succ_firm in list_choose_firm]
|
}) for succ_firm in lst_choose_firm]
|
||||||
G_Firm.add_edges_from(list_added_edges)
|
G_Firm.add_edges_from(lst_add_edge)
|
||||||
# print('-' * 20)
|
|
||||||
|
|
||||||
self.firm_network = ap.Network(self, G_Firm)
|
self.firm_network = ap.Network(self, G_Firm)
|
||||||
self.product_network = ap.Network(self, G_bom)
|
self.product_network = ap.Network(self, G_bom)
|
||||||
# print([node.label for node in self.firm_network.nodes])
|
|
||||||
# print([list(self.firm_network.graph.predecessors(node))
|
|
||||||
# for node in self.firm_network.nodes])
|
|
||||||
# print([self.firm_network.graph.nodes[node.label]['Name']
|
|
||||||
# for node in self.firm_network.nodes])
|
|
||||||
# print([v for v in self.firm_network.graph.nodes(data=True)])
|
|
||||||
|
|
||||||
# init product
|
# init product
|
||||||
for ag_node, attr in self.product_network.graph.nodes(data=True):
|
for ag_node, attr in self.product_network.graph.nodes(data=True):
|
||||||
product_agent = ProductAgent(self,
|
product = ProductAgent(self, code=ag_node.label, name=attr['Name'])
|
||||||
code=ag_node.label,
|
self.product_network.add_agents([product], [ag_node])
|
||||||
name=attr['Name'])
|
self.a_lst_total_products = ap.AgentList(self,
|
||||||
self.product_network.add_agents([product_agent], [ag_node])
|
|
||||||
self.a_list_total_products = ap.AgentList(self,
|
|
||||||
self.product_network.agents)
|
self.product_network.agents)
|
||||||
|
|
||||||
# init firm
|
# init firm
|
||||||
|
@ -149,201 +108,164 @@ class Model(ap.Model):
|
||||||
name=attr['Name'],
|
name=attr['Name'],
|
||||||
type_region=attr['Type_Region'],
|
type_region=attr['Type_Region'],
|
||||||
revenue_log=attr['Revenue_Log'],
|
revenue_log=attr['Revenue_Log'],
|
||||||
a_list_product=self.a_list_total_products.select([
|
a_lst_product=self.a_lst_total_products.select([
|
||||||
code in attr['Product_Code']
|
code in attr['Product_Code']
|
||||||
for code in self.a_list_total_products.code
|
for code in self.a_lst_total_products.code
|
||||||
]))
|
]))
|
||||||
# init capacity based on discrete uniform distribution
|
# init extra capacity based on discrete uniform distribution
|
||||||
# list_out_edges = list(
|
for product in firm_agent.a_lst_product:
|
||||||
# self.firm_network.graph.out_edges(ag_node,
|
|
||||||
# keys=True,
|
|
||||||
# data='Product'))
|
|
||||||
# for product in firm_agent.a_list_product:
|
|
||||||
# capacity = len([
|
|
||||||
# edge for edge in list_out_edges if edge[-1] ==
|
|
||||||
# product.code])
|
|
||||||
# firm_agent.dct_prod_capacity[product] = capacity
|
|
||||||
for product in firm_agent.a_list_product:
|
|
||||||
firm_agent.dct_prod_capacity[product] = self.nprandom.integers(
|
firm_agent.dct_prod_capacity[product] = self.nprandom.integers(
|
||||||
firm_agent.revenue_log / 5, firm_agent.revenue_log / 5 + 2)
|
firm_agent.revenue_log / 5, firm_agent.revenue_log / 5 + 2)
|
||||||
# print(firm_agent.name, firm_agent.dct_prod_capacity)
|
# print(firm_agent.name, firm_agent.dct_prod_capacity)
|
||||||
|
|
||||||
self.firm_network.add_agents([firm_agent], [ag_node])
|
self.firm_network.add_agents([firm_agent], [ag_node])
|
||||||
self.a_list_total_firms = ap.AgentList(self, self.firm_network.agents)
|
self.a_lst_total_firms = ap.AgentList(self, self.firm_network.agents)
|
||||||
# print(list(zip(self.a_list_total_firms.code,
|
|
||||||
# self.a_list_total_firms.name,
|
|
||||||
# self.a_list_total_firms.capacity)))
|
|
||||||
|
|
||||||
# init dct_list_remove_firm_prod (from string to agent)
|
# init dct_list_remove_firm_prod (from string to agent)
|
||||||
t_dct = {}
|
t_dct = {}
|
||||||
for firm_code, list_product in self.dct_list_remove_firm_prod.items():
|
for firm_code, lst_product in self.dct_lst_remove_firm_prod.items():
|
||||||
firm = self.a_list_total_firms.select(
|
firm = self.a_lst_total_firms.select(
|
||||||
self.a_list_total_firms.code == firm_code)[0]
|
self.a_lst_total_firms.code == firm_code)[0]
|
||||||
t_dct[firm] = self.a_list_total_products.select([
|
t_dct[firm] = self.a_lst_total_products.select([
|
||||||
code in list_product
|
code in lst_product for code in self.a_lst_total_products.code
|
||||||
for code in self.a_list_total_products.code
|
|
||||||
])
|
])
|
||||||
self.dct_list_remove_firm_prod = t_dct
|
self.dct_lst_remove_firm_prod = t_dct
|
||||||
self.dct_list_disrupt_firm_prod = t_dct
|
self.dct_lst_disrupt_firm_prod = t_dct
|
||||||
|
|
||||||
# init output
|
# init output
|
||||||
self.list_dct_list_remove_firm_prod = []
|
self.lst_dct_lst_remove_firm_prod = []
|
||||||
self.list_dct_list_disrupt_firm_prod = []
|
self.lst_dct_lst_disrupt_firm_prod = []
|
||||||
|
|
||||||
# set the initial firm product that are removed
|
# set the initial firm product that are removed
|
||||||
for firm, a_list_product in self.dct_list_remove_firm_prod.items():
|
for firm, a_lst_product in self.dct_lst_remove_firm_prod.items():
|
||||||
for product in a_list_product:
|
for product in a_lst_product:
|
||||||
assert product in firm.a_list_product, \
|
assert product in firm.a_lst_product, \
|
||||||
f"product {product.code} not in firm {firm.code}"
|
f"product {product.code} not in firm {firm.code}"
|
||||||
firm.a_list_product_removed.append(product)
|
firm.a_lst_product_removed.append(product)
|
||||||
|
|
||||||
# draw network
|
# draw network
|
||||||
# self.draw_network()
|
# self.draw_network()
|
||||||
|
|
||||||
def update(self):
|
def update(self):
|
||||||
self.a_list_total_firms.clean_before_time_step()
|
self.a_lst_total_firms.clean_before_time_step()
|
||||||
# output
|
# output
|
||||||
self.list_dct_list_remove_firm_prod.append(
|
self.lst_dct_lst_remove_firm_prod.append(
|
||||||
(self.t, self.dct_list_remove_firm_prod))
|
(self.t, self.dct_lst_remove_firm_prod))
|
||||||
self.list_dct_list_disrupt_firm_prod.append(
|
self.lst_dct_lst_disrupt_firm_prod.append(
|
||||||
(self.t, self.dct_list_disrupt_firm_prod))
|
(self.t, self.dct_lst_disrupt_firm_prod))
|
||||||
|
|
||||||
# stop simulation if reached terminal number of iteration
|
# stop simulation if reached terminal number of iteration
|
||||||
if self.t == self.int_n_iter or len(
|
if self.t == self.int_n_iter or len(
|
||||||
self.dct_list_remove_firm_prod) == 0:
|
self.dct_lst_remove_firm_prod) == 0:
|
||||||
self.int_stop_times = self.t
|
self.int_stop_times = self.t
|
||||||
print(self.int_stop_times, self.t)
|
|
||||||
self.stop()
|
self.stop()
|
||||||
|
|
||||||
def step(self):
|
def step(self):
|
||||||
# shuffle self.dct_list_remove_firm_prod
|
|
||||||
# dct_key_list = list(self.dct_list_remove_firm_prod.keys())
|
|
||||||
# self.nprandom.shuffle(dct_key_list)
|
|
||||||
# self.dct_list_remove_firm_prod = {
|
|
||||||
# key: self.dct_list_remove_firm_prod[key].shuffle()
|
|
||||||
# for key in dct_key_list
|
|
||||||
# }
|
|
||||||
# print(self.dct_list_remove_firm_prod)
|
|
||||||
|
|
||||||
print('\n', '=' * 20, 'step', self.t, '=' * 20)
|
print('\n', '=' * 20, 'step', self.t, '=' * 20)
|
||||||
print(
|
print(
|
||||||
'dct_list_remove_firm_prod', {
|
'dct_list_remove_firm_prod', {
|
||||||
key.name: value.code
|
key.name: value.code
|
||||||
for key, value in self.dct_list_remove_firm_prod.items()
|
for key, value in self.dct_lst_remove_firm_prod.items()
|
||||||
})
|
})
|
||||||
|
|
||||||
# remove_edge_to_cus_and_cus_up_prod
|
# remove_edge_to_cus_and_cus_up_prod
|
||||||
for firm, a_list_product in self.dct_list_remove_firm_prod.items():
|
for firm, a_lst_product in self.dct_lst_remove_firm_prod.items():
|
||||||
for product in a_list_product:
|
for product in a_lst_product:
|
||||||
firm.remove_edge_to_cus_remove_cus_up_prod(product)
|
firm.remove_edge_to_cus_remove_cus_up_prod(product)
|
||||||
|
|
||||||
for n_trial in range(self.int_n_max_trial):
|
for n_trial in range(self.int_n_max_trial):
|
||||||
print('=' * 10, 'trial', n_trial, '=' * 10)
|
print('=' * 10, 'trial', n_trial, '=' * 10)
|
||||||
# seek_alt_supply
|
# seek_alt_supply
|
||||||
# shuffle self.a_list_total_firms
|
# shuffle self.a_lst_total_firms
|
||||||
self.a_list_total_firms = self.a_list_total_firms.shuffle()
|
self.a_lst_total_firms = self.a_lst_total_firms.shuffle()
|
||||||
for firm in self.a_list_total_firms:
|
for firm in self.a_lst_total_firms:
|
||||||
if len(firm.a_list_up_product_removed) > 0:
|
if len(firm.a_lst_up_product_removed) > 0:
|
||||||
# print(firm.name)
|
|
||||||
# print(firm.a_list_up_product_removed.code)
|
|
||||||
firm.seek_alt_supply()
|
firm.seek_alt_supply()
|
||||||
|
|
||||||
# handle_request
|
# handle_request
|
||||||
# shuffle self.a_list_total_firms
|
# shuffle self.a_lst_total_firms
|
||||||
self.a_list_total_firms = self.a_list_total_firms.shuffle()
|
self.a_lst_total_firms = self.a_lst_total_firms.shuffle()
|
||||||
for firm in self.a_list_total_firms:
|
for firm in self.a_lst_total_firms:
|
||||||
if len(firm.dct_request_prod_from_firm) > 0:
|
if len(firm.dct_request_prod_from_firm) > 0:
|
||||||
firm.handle_request()
|
firm.handle_request()
|
||||||
|
|
||||||
# reset dct_request_prod_from_firm
|
# reset dct_request_prod_from_firm
|
||||||
self.a_list_total_firms.clean_before_trial()
|
self.a_lst_total_firms.clean_before_trial()
|
||||||
# do not use:
|
# do not use:
|
||||||
# self.a_list_total_firms.dct_request_prod_from_firm = {} why?
|
# self.a_lst_total_firms.dct_request_prod_from_firm = {} why?
|
||||||
|
|
||||||
# based on a_list_up_product_removed,
|
# based on a_lst_up_product_removed
|
||||||
# update a_list_product_disrupted / a_list_product_removed
|
# update a_lst_product_disrupted / a_lst_product_removed
|
||||||
# update dct_list_disrupt_firm_prod / dct_list_remove_firm_prod
|
# update dct_lst_disrupt_firm_prod / dct_lst_remove_firm_prod
|
||||||
self.dct_list_remove_firm_prod = {}
|
self.dct_lst_remove_firm_prod = {}
|
||||||
self.dct_list_disrupt_firm_prod = {}
|
self.dct_lst_disrupt_firm_prod = {}
|
||||||
for firm in self.a_list_total_firms:
|
for firm in self.a_lst_total_firms:
|
||||||
if len(firm.a_list_up_product_removed) > 0:
|
if len(firm.a_lst_up_product_removed) > 0:
|
||||||
print(firm.name, 'a_list_up_product_removed', [
|
print(firm.name, 'a_lst_up_product_removed', [
|
||||||
product.code for product in firm.a_list_up_product_removed
|
product.code for product in firm.a_lst_up_product_removed
|
||||||
])
|
])
|
||||||
for product in firm.a_list_product:
|
for product in firm.a_lst_product:
|
||||||
n_up_product_removed = 0
|
n_up_product_removed = 0
|
||||||
for up_product_removed in firm.a_list_up_product_removed:
|
for up_product_removed in firm.a_lst_up_product_removed:
|
||||||
if product in up_product_removed.a_successors():
|
if product in up_product_removed.a_successors():
|
||||||
n_up_product_removed += 1
|
n_up_product_removed += 1
|
||||||
if n_up_product_removed == 0:
|
if n_up_product_removed == 0:
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
# update a_list_product_disrupted / dct_list_disrupt_firm_prod
|
# update a_lst_product_disrupted / dct_lst_disrupt_firm_prod
|
||||||
if product not in firm.a_list_product_disrupted:
|
if product not in firm.a_lst_product_disrupted:
|
||||||
firm.a_list_product_disrupted.append(product)
|
firm.a_lst_product_disrupted.append(product)
|
||||||
if firm in self.dct_list_disrupt_firm_prod.keys():
|
if firm in self.dct_lst_disrupt_firm_prod.keys():
|
||||||
self.dct_list_disrupt_firm_prod[firm].append(
|
self.dct_lst_disrupt_firm_prod[firm].append(
|
||||||
product)
|
product)
|
||||||
else:
|
else:
|
||||||
self.dct_list_disrupt_firm_prod[
|
self.dct_lst_disrupt_firm_prod[
|
||||||
firm] = ap.AgentList(
|
firm] = ap.AgentList(
|
||||||
self.model, [product])
|
self.model, [product])
|
||||||
# update a_list_product_removed / dct_list_remove_firm_prod
|
# update a_lst_product_removed / dct_list_remove_firm_prod
|
||||||
|
# mark disrupted firm as removed based conditionally
|
||||||
lost_percent = n_up_product_removed / len(
|
lost_percent = n_up_product_removed / len(
|
||||||
product.a_predecessors())
|
product.a_predecessors())
|
||||||
list_revenue_log = self.a_list_total_firms.revenue_log
|
lst_size = self.a_lst_total_firms.revenue_log
|
||||||
std_size = (firm.revenue_log - min(list_revenue_log) +
|
std_size = (firm.revenue_log - min(lst_size) +
|
||||||
1) / (max(list_revenue_log) -
|
1) / (max(lst_size) - min(lst_size) + 1)
|
||||||
min(list_revenue_log) + 1)
|
prod_remove = 1 - std_size * (1 - lost_percent)
|
||||||
p_remove = 1 - std_size * (1 - lost_percent)
|
if self.nprandom.choice(
|
||||||
flag = self.nprandom.choice([1, 0],
|
[True, False], p=[prod_remove, 1 - prod_remove]):
|
||||||
p=[p_remove, 1 - p_remove])
|
firm.a_lst_product_removed.append(product)
|
||||||
# flag = 1
|
if firm in self.dct_lst_remove_firm_prod.keys():
|
||||||
if flag == 1:
|
self.dct_lst_remove_firm_prod[firm].append(
|
||||||
firm.a_list_product_removed.append(product)
|
|
||||||
# if firm in
|
|
||||||
# self.dct_list_remove_firm_prod[firm] = firm.a_list_product_removed
|
|
||||||
if firm in self.dct_list_remove_firm_prod.keys():
|
|
||||||
self.dct_list_remove_firm_prod[firm].append(
|
|
||||||
product)
|
product)
|
||||||
else:
|
else:
|
||||||
self.dct_list_remove_firm_prod[
|
self.dct_lst_remove_firm_prod[
|
||||||
firm] = ap.AgentList(
|
firm] = ap.AgentList(
|
||||||
self.model, [product])
|
self.model, [product])
|
||||||
|
|
||||||
# # update the firm that is removed
|
|
||||||
# self.dct_list_remove_firm_prod = {}
|
|
||||||
# for firm in self.a_list_total_firms:
|
|
||||||
# if len(firm.a_list_product_removed) > 0:
|
|
||||||
# self.dct_list_remove_firm_prod[
|
|
||||||
# firm] = firm.a_list_product_removed
|
|
||||||
# print(self.dct_list_remove_firm_prod)
|
|
||||||
print(
|
print(
|
||||||
'dct_list_remove_firm_prod', {
|
'dct_list_remove_firm_prod', {
|
||||||
key.name: value.code
|
key.name: value.code
|
||||||
for key, value in self.dct_list_remove_firm_prod.items()
|
for key, value in self.dct_lst_remove_firm_prod.items()
|
||||||
})
|
})
|
||||||
|
|
||||||
def end(self):
|
def end(self):
|
||||||
print('/' * 20, 'output', '/' * 20)
|
print('/' * 20, 'output', '/' * 20)
|
||||||
print('dct_list_remove_firm_prod')
|
print('dct_list_remove_firm_prod')
|
||||||
for t, dct in self.list_dct_list_remove_firm_prod:
|
for t, dct in self.lst_dct_lst_remove_firm_prod:
|
||||||
for firm, a_list_product in dct.items():
|
for firm, a_lst_product in dct.items():
|
||||||
for product in a_list_product:
|
for product in a_lst_product:
|
||||||
print(t, firm.name, product.code)
|
print(t, firm.name, product.code)
|
||||||
print('dct_list_disrupt_firm_prod')
|
print('dct_lst_disrupt_firm_prod')
|
||||||
for t, dct in self.list_dct_list_disrupt_firm_prod:
|
for t, dct in self.lst_dct_lst_disrupt_firm_prod:
|
||||||
for firm, a_list_product in dct.items():
|
for firm, a_lst_product in dct.items():
|
||||||
for product in a_list_product:
|
for product in a_lst_product:
|
||||||
print(t, firm.name, product.code)
|
print(t, firm.name, product.code)
|
||||||
|
|
||||||
qry_result = db_session.query(Result).filter_by(s_id=self.sample.id)
|
qry_result = db_session.query(Result).filter_by(s_id=self.sample.id)
|
||||||
if qry_result.count() == 0:
|
if qry_result.count() == 0:
|
||||||
lst_result_info = []
|
lst_result_info = []
|
||||||
for t, dct in self.list_dct_list_disrupt_firm_prod:
|
for t, dct in self.lst_dct_lst_disrupt_firm_prod:
|
||||||
for firm, a_list_product in dct.items():
|
for firm, a_lst_product in dct.items():
|
||||||
for product in a_list_product:
|
for product in a_lst_product:
|
||||||
# print(t, firm.name, product.code)
|
|
||||||
db_r = Result(s_id=self.sample.id,
|
db_r = Result(s_id=self.sample.id,
|
||||||
id_firm=firm.code,
|
id_firm=firm.code,
|
||||||
id_product=product.code,
|
id_product=product.code,
|
||||||
|
@ -352,11 +274,10 @@ class Model(ap.Model):
|
||||||
lst_result_info.append(db_r)
|
lst_result_info.append(db_r)
|
||||||
db_session.bulk_save_objects(lst_result_info)
|
db_session.bulk_save_objects(lst_result_info)
|
||||||
db_session.commit()
|
db_session.commit()
|
||||||
for t, dct in self.list_dct_list_remove_firm_prod:
|
for t, dct in self.lst_dct_lst_remove_firm_prod:
|
||||||
for firm, a_list_product in dct.items():
|
for firm, a_lst_product in dct.items():
|
||||||
for product in a_list_product:
|
for product in a_lst_product:
|
||||||
# print(t, firm.name, product.code)
|
# only firm disrupted can be removed theoretically
|
||||||
# only firm disrupted can be removed
|
|
||||||
qry_f_p = db_session.query(Result).filter(
|
qry_f_p = db_session.query(Result).filter(
|
||||||
Result.s_id == self.sample.id,
|
Result.s_id == self.sample.id,
|
||||||
Result.id_firm == firm.code,
|
Result.id_firm == firm.code,
|
||||||
|
@ -364,8 +285,8 @@ class Model(ap.Model):
|
||||||
if qry_f_p.count() == 1:
|
if qry_f_p.count() == 1:
|
||||||
qry_f_p.update({"is_removed": True})
|
qry_f_p.update({"is_removed": True})
|
||||||
db_session.commit()
|
db_session.commit()
|
||||||
self.sample.is_done_flag, self.sample.computer_name = 1, platform.node(
|
self.sample.is_done_flag = 1
|
||||||
)
|
self.sample.computer_name = platform.node()
|
||||||
self.sample.stop_t = self.int_stop_times
|
self.sample.stop_t = self.int_stop_times
|
||||||
db_session.commit()
|
db_session.commit()
|
||||||
|
|
||||||
|
@ -401,7 +322,3 @@ class Model(ap.Model):
|
||||||
edge_label,
|
edge_label,
|
||||||
font_size=4)
|
font_size=4)
|
||||||
plt.savefig("network.png")
|
plt.savefig("network.png")
|
||||||
|
|
||||||
|
|
||||||
# model = Model(dct_sample_para)
|
|
||||||
# model.run()
|
|
||||||
|
|
2
orm.py
2
orm.py
|
@ -45,7 +45,7 @@ class Experiment(Base):
|
||||||
|
|
||||||
# variables
|
# variables
|
||||||
n_max_trial = Column(Integer, nullable=False)
|
n_max_trial = Column(Integer, nullable=False)
|
||||||
dct_list_init_remove_firm_prod = Column(PickleType, nullable=False)
|
dct_lst_init_remove_firm_prod = Column(PickleType, nullable=False)
|
||||||
|
|
||||||
sample = relationship('Sample', back_populates='experiment', lazy='dynamic')
|
sample = relationship('Sample', back_populates='experiment', lazy='dynamic')
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue