dct_prod_up_prod_stat + no need for dct_list_remove_firm_prod/dct_list_disrupt_firm_prod

This commit is contained in:
HaoYizhi 2023-06-18 17:29:11 +08:00
parent 09ea2e9527
commit dd8a786f6c
8 changed files with 247 additions and 129 deletions

Binary file not shown.

Binary file not shown.

View File

@ -83,9 +83,9 @@ class ControllerDB:
# list_dct = [{'133': ['1.4.4.1']}]
# list_dct = [{'2': ['1.1.3']}]
# list_dct = [{'135': ['1.3.2.1']}]
# list_dct = [{'79': ['2.1.3.4']}]
list_dct = [{'79': ['2.1.3.4']}]
# list_dct = [{'99': ['1.3.3']}]
list_dct = [{'41': ['1.4.5']}]
# list_dct = [{'41': ['1.4.5']}]
# fill g_bom
BomNodes = pd.read_csv('BomNodes.csv', index_col=0)

128
firm.py
View File

@ -14,10 +14,20 @@ class FirmAgent(ap.Agent):
self.a_lst_product = a_lst_product
self.dct_prod_capacity = dict.fromkeys(self.a_lst_product)
self.a_lst_up_product_removed = ap.AgentList(self.model, [])
self.a_lst_product_disrupted = ap.AgentList(self.model, [])
# self.a_lst_up_product_removed = ap.AgentList(self.model, [])
# self.a_lst_product_disrupted = ap.AgentList(self.model, [])
self.a_lst_product_removed = ap.AgentList(self.model, [])
self.dct_prod_up_prod_stat = {}
for prod in a_lst_product:
self.dct_prod_up_prod_stat[prod] = {
# Normal / Disrupted / Removed + time step
'status': [('N', 0)],
# have or have no supply
'supply': dict.fromkeys(prod.a_predecessors(), True)
}
# print(self.dct_prod_up_prod_stat)
self.dct_n_trial_up_prod_removed = {}
self.dct_cand_alt_supply_up_prod_removed = {}
self.dct_request_prod_from_firm = {}
@ -52,30 +62,43 @@ class FirmAgent(ap.Agent):
if self.model.nprandom.choice([True, False],
p=[prod_remove,
1 - prod_remove]):
# print(self.name, remove_product.code, 'affect',
# customer.name)
if remove_product not in \
customer.a_lst_up_product_removed:
customer.a_lst_up_product_removed.append(
remove_product)
customer.dct_n_trial_up_prod_removed[
remove_product] = 0
# if remove_product not in \
# customer.a_lst_up_product_removed:
# customer.a_lst_up_product_removed.append(
# remove_product)
# customer.dct_n_trial_up_prod_removed[
# remove_product] = 0
def seek_alt_supply(self):
for product in self.a_lst_up_product_removed:
# print(f"{self.name} seek alt supply for {product.code}")
if self.dct_n_trial_up_prod_removed[
product] <= self.model.int_n_max_trial:
if self.dct_n_trial_up_prod_removed[product] == 0:
# select a list of candidate firm that has the product
self.dct_cand_alt_supply_up_prod_removed[product] = \
self.model.a_lst_total_firms.select([
product in firm.a_lst_product
and product not in firm.a_lst_product_removed
for firm in self.model.a_lst_total_firms
])
if not self.dct_cand_alt_supply_up_prod_removed[product]:
continue
for prod in customer.dct_prod_up_prod_stat.keys():
if remove_product in \
customer.dct_prod_up_prod_stat[
prod]['supply'].keys():
customer.dct_prod_up_prod_stat[
prod]['supply'][remove_product] = False
customer.dct_prod_up_prod_stat[
prod]['status'].append(('D', self.model.t))
customer.dct_n_trial_up_prod_removed[
remove_product] = 0
print(self.name, remove_product.code, 'affect',
customer.name, prod.code)
# print(customer.dct_prod_up_prod_stat)
def seek_alt_supply(self, product):
# para product is the product that self is seeking
# for product in self.a_lst_up_product_removed:
print(f"{self.name} seek alt supply for {product.code}")
if self.dct_n_trial_up_prod_removed[
product] <= self.model.int_n_max_trial:
if self.dct_n_trial_up_prod_removed[product] == 0:
# select a list of candidate firm that has the product
self.dct_cand_alt_supply_up_prod_removed[product] = \
self.model.a_lst_total_firms.select([
product in firm.a_lst_product
and product not in firm.a_lst_product_removed
for firm in self.model.a_lst_total_firms
])
if self.dct_cand_alt_supply_up_prod_removed[product]:
# select based on connection
lst_firm_connect = []
if self.is_prf_conn:
@ -99,8 +122,8 @@ class FirmAgent(ap.Agent):
if self.is_prf_size:
lst_size = \
[size for size in
self.dct_cand_alt_supply_up_prod_removed[
product].revenue_log]
self.dct_cand_alt_supply_up_prod_removed[
product].revenue_log]
lst_prob = [size / sum(lst_size)
for size in lst_size]
select_alt_supply = self.model.nprandom.choice(
@ -123,10 +146,10 @@ class FirmAgent(ap.Agent):
else:
select_alt_supply = \
self.model.nprandom.choice(lst_firm_connect)
# print(
# f"{self.name} selct alt supply for {product.code} "
# f"from {select_alt_supply.name}"
# )
print(
f"{self.name} selct alt supply for {product.code} "
f"from {select_alt_supply.name}"
)
assert product in select_alt_supply.a_lst_product, \
f"{select_alt_supply} \
does not produce requested product {product}"
@ -139,17 +162,17 @@ class FirmAgent(ap.Agent):
select_alt_supply.dct_request_prod_from_firm[product] = [
self
]
# print(
# select_alt_supply.name, 'dct_request_prod_from_firm', {
# key.code: [v.name for v in value]
# for key, value in
# select_alt_supply.dct_request_prod_from_firm.items()
# })
print(
select_alt_supply.name, 'dct_request_prod_from_firm', {
key.code: [v.name for v in value]
for key, value in
select_alt_supply.dct_request_prod_from_firm.items()
})
self.dct_n_trial_up_prod_removed[product] += 1
def handle_request(self):
# print(self.name, 'handle_request')
print(self.name, 'handle_request')
for product, lst_firm in self.dct_request_prod_from_firm.items():
if self.dct_prod_capacity[product] > 0:
if len(lst_firm) == 0:
@ -210,6 +233,7 @@ class FirmAgent(ap.Agent):
self.accept_request(select_customer, product)
def accept_request(self, down_firm, product):
# para product is the product that self is selling
prod_accept = self.flt_diff_new_conn
if self.model.nprandom.choice([True, False],
p=[prod_accept, 1 - prod_accept]):
@ -221,11 +245,23 @@ class FirmAgent(ap.Agent):
])
self.dct_prod_capacity[product] -= 1
self.dct_request_prod_from_firm[product].remove(down_firm)
down_firm.a_lst_up_product_removed.remove(product)
# print(
# f"{self.name} accept {product.code} request "
# f"from {down_firm.name}"
# )
# down_firm.a_lst_up_product_removed.remove(product)
for prod in down_firm.dct_prod_up_prod_stat.keys():
if product in down_firm.dct_prod_up_prod_stat[
prod]['supply'].keys():
down_firm.dct_prod_up_prod_stat[
prod]['supply'][product] = True
down_firm.dct_prod_up_prod_stat[
prod]['status'].append(('N', self.model.t))
# print(down_firm.dct_prod_up_prod_stat)
del down_firm.dct_n_trial_up_prod_removed[product]
del down_firm.dct_cand_alt_supply_up_prod_removed[product]
print(
f"{self.name} accept {product.code} request "
f"from {down_firm.name}"
)
else:
down_firm.dct_cand_alt_supply_up_prod_removed[product].remove(self)
@ -233,8 +269,10 @@ class FirmAgent(ap.Agent):
self.dct_request_prod_from_firm = {}
def clean_before_time_step(self):
self.dct_n_trial_up_prod_removed = {}
self.a_lst_up_product_removed = ap.AgentList(self.model, [])
self.dct_n_trial_up_prod_removed = \
dict.fromkeys(self.dct_n_trial_up_prod_removed.keys(), 0)
self.dct_cand_alt_supply_up_prod_removed = {}
# self.a_lst_up_product_removed = ap.AgentList(self.model, [])
def get_firm_network_node(self):
return self.firm_network.positions[self]

210
model.py
View File

@ -235,11 +235,13 @@ class Model(ap.Model):
code in lst_product for code in self.a_lst_total_products.code
])
self.dct_lst_remove_firm_prod = t_dct
self.dct_lst_disrupt_firm_prod = t_dct
# self.dct_lst_disrupt_firm_prod = t_dct
# init output
self.lst_dct_lst_remove_firm_prod = []
self.lst_dct_lst_disrupt_firm_prod = []
# # init output
# self.lst_dct_lst_remove_firm_prod = []
# self.lst_dct_lst_disrupt_firm_prod = []
# self.dct_ts_dct_a_lst_remove = {}
# set the initial firm product that are removed
for firm, a_lst_product in self.dct_lst_remove_firm_prod.items():
@ -247,6 +249,8 @@ class Model(ap.Model):
assert product in firm.a_lst_product, \
f"product {product.code} not in firm {firm.code}"
firm.a_lst_product_removed.append(product)
firm.dct_prod_up_prod_stat[
product]['status'].append(('R', self.t))
# proactive strategy
# get all the firm prod affected
@ -356,20 +360,34 @@ class Model(ap.Model):
def update(self):
self.a_lst_total_firms.clean_before_time_step()
# output
self.lst_dct_lst_remove_firm_prod.append(
(self.t, self.dct_lst_remove_firm_prod))
self.lst_dct_lst_disrupt_firm_prod.append(
(self.t, self.dct_lst_disrupt_firm_prod))
# # output
# self.lst_dct_lst_remove_firm_prod.append(
# (self.t, self.dct_lst_remove_firm_prod))
# self.lst_dct_lst_disrupt_firm_prod.append(
# (self.t, self.dct_lst_disrupt_firm_prod))
# stop simulation if reached terminal number of iteration
if self.t == self.int_n_iter or len(
self.dct_lst_remove_firm_prod) == 0:
self.int_stop_times = self.t
self.stop()
# # stop simulation if reached terminal number of iteration
# if self.t == self.int_n_iter or len(
# self.dct_lst_remove_firm_prod) == 0:
# self.int_stop_times = self.t
# self.stop()
if self.t > 0:
for firm in self.a_lst_total_firms:
for prod in firm.dct_prod_up_prod_stat.keys():
status, ts = firm.dct_prod_up_prod_stat[prod]['status'][-1]
if status == 'R' and ts != 0:
print("not stop because", firm.name, prod.code)
break
else:
continue
break
else:
self.int_stop_times = self.t
self.stop()
def step(self):
# print('\n', '=' * 20, 'step', self.t, '=' * 20)
print('\n', '=' * 20, 'step', self.t, '=' * 20)
# print(
# 'dct_list_remove_firm_prod', {
# key.name: value.code
@ -377,18 +395,33 @@ class Model(ap.Model):
# })
# remove_edge_to_cus_and_cus_up_prod
for firm, a_lst_product in self.dct_lst_remove_firm_prod.items():
for product in a_lst_product:
firm.remove_edge_to_cus_remove_cus_up_prod(product)
for firm in self.a_lst_total_firms:
for prod in firm.dct_prod_up_prod_stat.keys():
status, ts = firm.dct_prod_up_prod_stat[prod]['status'][-1]
if status == 'R' and ts == self.t-1:
firm.remove_edge_to_cus_remove_cus_up_prod(prod)
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
# shuffle self.a_lst_total_firms
self.a_lst_total_firms = self.a_lst_total_firms.shuffle()
for firm in self.a_lst_total_firms:
if len(firm.a_lst_up_product_removed) > 0:
firm.seek_alt_supply()
# if len(firm.a_lst_up_product_removed) > 0:
# firm.seek_alt_supply()
lst_seek_prod = []
for prod in firm.dct_prod_up_prod_stat.keys():
status = firm.dct_prod_up_prod_stat[prod]['status'][-1][0]
if status != 'N':
for supply in firm.dct_prod_up_prod_stat[
prod]['supply'].keys():
if not firm.dct_prod_up_prod_stat[
prod]['supply'][supply]:
lst_seek_prod.append(supply)
# commmon supply only seek once
lst_seek_prod = list(set(lst_seek_prod))
for supply in lst_seek_prod:
firm.seek_alt_supply(supply)
# handle_request
# shuffle self.a_lst_total_firms
@ -402,35 +435,43 @@ class Model(ap.Model):
# do not use:
# self.a_lst_total_firms.dct_request_prod_from_firm = {} why?
# based on a_lst_up_product_removed
# based on dct_prod_up_prod_stat
# update a_lst_product_disrupted / a_lst_product_removed
# update dct_lst_disrupt_firm_prod / dct_lst_remove_firm_prod
self.dct_lst_remove_firm_prod = {}
self.dct_lst_disrupt_firm_prod = {}
# self.dct_lst_remove_firm_prod = {}
# self.dct_lst_disrupt_firm_prod = {}
for firm in self.a_lst_total_firms:
if len(firm.a_lst_up_product_removed) > 0:
# print(firm.name, 'a_lst_up_product_removed', [
# product.code for product in firm.a_lst_up_product_removed
# ])
for product in firm.a_lst_product:
n_up_product_removed = 0
for up_product_removed in firm.a_lst_up_product_removed:
if product in up_product_removed.a_successors():
n_up_product_removed += 1
# if len(firm.a_lst_up_product_removed) > 0:
# print(firm.name, 'a_lst_up_product_removed', [
# product.code for product in firm.a_lst_up_product_removed
# ])
for product in firm.dct_prod_up_prod_stat.keys():
status = firm.dct_prod_up_prod_stat[product]['status'][-1][0]
if status == 'D':
print(firm.name, 'disrupted product: ', product.code)
n_up_product_removed = \
sum([not stat for stat in
firm.dct_prod_up_prod_stat[
product]['supply'].values()])
# for product in firm.a_lst_product:
# n_up_product_removed = 0
# for up_product_removed in firm.a_lst_up_product_removed:
# if product in up_product_removed.a_successors():
# n_up_product_removed += 1
if n_up_product_removed == 0:
continue
else:
# update a_lst_product_disrupted
# update dct_lst_disrupt_firm_prod
if product not in firm.a_lst_product_disrupted:
firm.a_lst_product_disrupted.append(product)
if firm in self.dct_lst_disrupt_firm_prod.keys():
self.dct_lst_disrupt_firm_prod[firm].append(
product)
else:
self.dct_lst_disrupt_firm_prod[
firm] = ap.AgentList(
self.model, [product])
# # update a_lst_product_disrupted
# # update dct_lst_disrupt_firm_prod
# if product not in firm.a_lst_product_disrupted:
# firm.a_lst_product_disrupted.append(product)
# if firm in self.dct_lst_disrupt_firm_prod.keys():
# self.dct_lst_disrupt_firm_prod[firm].append(
# product)
# else:
# self.dct_lst_disrupt_firm_prod[
# firm] = ap.AgentList(
# self.model, [product])
# update a_lst_product_removed
# update dct_list_remove_firm_prod
# mark disrupted firm as removed based conditionally
@ -457,13 +498,20 @@ class Model(ap.Model):
p=[prob_remove,
1 - prob_remove]):
firm.a_lst_product_removed.append(product)
if firm in self.dct_lst_remove_firm_prod.keys():
self.dct_lst_remove_firm_prod[firm].append(
product)
else:
self.dct_lst_remove_firm_prod[
firm] = ap.AgentList(
self.model, [product])
# if firm in self.dct_lst_remove_firm_prod.keys():
# self.dct_lst_remove_firm_prod[firm].append(
# product)
# else:
# self.dct_lst_remove_firm_prod[
# firm] = ap.AgentList(
# self.model, [product])
firm.dct_prod_up_prod_stat[
product]['status'].append(('R', self.t))
print(firm.name, 'removed product: ', product.code)
else:
firm.dct_prod_up_prod_stat[
product]['status'].append(('N', self.t))
# print(
# 'dct_list_remove_firm_prod', {
@ -472,7 +520,7 @@ class Model(ap.Model):
# })
def end(self):
# print('/' * 20, 'output', '/' * 20)
print('/' * 20, 'output', '/' * 20)
# print('dct_list_remove_firm_prod')
# for t, dct in self.lst_dct_lst_remove_firm_prod:
# for firm, a_lst_product in dct.items():
@ -484,35 +532,35 @@ class Model(ap.Model):
# for product in a_lst_product:
# print(t, firm.name, product.code)
qry_result = db_session.query(Result).filter_by(s_id=self.sample.id)
if qry_result.count() == 0:
lst_result_info = []
for t, dct in self.lst_dct_lst_disrupt_firm_prod:
for firm, a_lst_product in dct.items():
for product in a_lst_product:
db_r = Result(s_id=self.sample.id,
id_firm=firm.code,
id_product=product.code,
ts=t,
is_disrupted=True)
lst_result_info.append(db_r)
db_session.bulk_save_objects(lst_result_info)
db_session.commit()
for t, dct in self.lst_dct_lst_remove_firm_prod:
for firm, a_lst_product in dct.items():
for product in a_lst_product:
# only firm disrupted can be removed theoretically
qry_f_p = db_session.query(Result).filter(
Result.s_id == self.sample.id,
Result.id_firm == firm.code,
Result.id_product == product.code)
if qry_f_p.count() == 1:
qry_f_p.update({"is_removed": True})
db_session.commit()
self.sample.is_done_flag = 1
self.sample.computer_name = platform.node()
self.sample.stop_t = self.int_stop_times
db_session.commit()
# qry_result = db_session.query(Result).filter_by(s_id=self.sample.id)
# if qry_result.count() == 0:
# lst_result_info = []
# for t, dct in self.lst_dct_lst_disrupt_firm_prod:
# for firm, a_lst_product in dct.items():
# for product in a_lst_product:
# db_r = Result(s_id=self.sample.id,
# id_firm=firm.code,
# id_product=product.code,
# ts=t,
# is_disrupted=True)
# lst_result_info.append(db_r)
# db_session.bulk_save_objects(lst_result_info)
# db_session.commit()
# for t, dct in self.lst_dct_lst_remove_firm_prod:
# for firm, a_lst_product in dct.items():
# for product in a_lst_product:
# # only firm disrupted can be removed theoretically
# qry_f_p = db_session.query(Result).filter(
# Result.s_id == self.sample.id,
# Result.id_firm == firm.code,
# Result.id_product == product.code)
# if qry_f_p.count() == 1:
# qry_f_p.update({"is_removed": True})
# db_session.commit()
# self.sample.is_done_flag = 1
# self.sample.computer_name = platform.node()
# self.sample.stop_t = self.int_stop_times
# db_session.commit()
def draw_network(self):
import matplotlib.pyplot as plt

View File

@ -266,6 +266,38 @@
" )\n",
"lst_choose_firm"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 0\n",
"0 1\n",
"0 2\n",
"1 0\n",
"1 1\n",
"break\n"
]
}
],
"source": [
"\n",
"for j in range(3):\n",
" for k in range(3):\n",
" print(j, k)\n",
" if j == k == 1:\n",
" print('break')\n",
" break\n",
" else:\n",
" continue\n",
" break\n",
"\n"
]
}
],
"metadata": {

View File

@ -1,2 +1,2 @@
n_max_trial,prf_size,prf_conn,cap_limit_prob_type,cap_limit_level,diff_new_conn,crit_supplier,diff_remove,proactive_ratio,netw_prf_n
10,TRUE,TRUE,uniform,10,0.5,1,1,0,2
10,TRUE,TRUE,uniform,10,0.1,1,0.01,0,2

1 n_max_trial prf_size prf_conn cap_limit_prob_type cap_limit_level diff_new_conn crit_supplier diff_remove proactive_ratio netw_prf_n
2 10 TRUE TRUE uniform 10 0.5 0.1 1 1 0.01 0 2