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 = [{'133': ['1.4.4.1']}]
# list_dct = [{'2': ['1.1.3']}] # list_dct = [{'2': ['1.1.3']}]
# list_dct = [{'135': ['1.3.2.1']}] # 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 = [{'99': ['1.3.3']}]
list_dct = [{'41': ['1.4.5']}] # list_dct = [{'41': ['1.4.5']}]
# fill g_bom # fill g_bom
BomNodes = pd.read_csv('BomNodes.csv', index_col=0) 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.a_lst_product = a_lst_product
self.dct_prod_capacity = dict.fromkeys(self.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_up_product_removed = ap.AgentList(self.model, [])
self.a_lst_product_disrupted = ap.AgentList(self.model, []) # self.a_lst_product_disrupted = ap.AgentList(self.model, [])
self.a_lst_product_removed = 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_n_trial_up_prod_removed = {}
self.dct_cand_alt_supply_up_prod_removed = {} self.dct_cand_alt_supply_up_prod_removed = {}
self.dct_request_prod_from_firm = {} self.dct_request_prod_from_firm = {}
@ -52,30 +62,43 @@ class FirmAgent(ap.Agent):
if self.model.nprandom.choice([True, False], if self.model.nprandom.choice([True, False],
p=[prod_remove, p=[prod_remove,
1 - prod_remove]): 1 - prod_remove]):
# print(self.name, remove_product.code, 'affect', # if remove_product not in \
# customer.name) # customer.a_lst_up_product_removed:
if remove_product not in \ # customer.a_lst_up_product_removed.append(
customer.a_lst_up_product_removed: # remove_product)
customer.a_lst_up_product_removed.append( # customer.dct_n_trial_up_prod_removed[
remove_product) # remove_product] = 0
customer.dct_n_trial_up_prod_removed[
remove_product] = 0
def seek_alt_supply(self): for prod in customer.dct_prod_up_prod_stat.keys():
for product in self.a_lst_up_product_removed: if remove_product in \
# print(f"{self.name} seek alt supply for {product.code}") customer.dct_prod_up_prod_stat[
if self.dct_n_trial_up_prod_removed[ prod]['supply'].keys():
product] <= self.model.int_n_max_trial: customer.dct_prod_up_prod_stat[
if self.dct_n_trial_up_prod_removed[product] == 0: prod]['supply'][remove_product] = False
# select a list of candidate firm that has the product customer.dct_prod_up_prod_stat[
self.dct_cand_alt_supply_up_prod_removed[product] = \ prod]['status'].append(('D', self.model.t))
self.model.a_lst_total_firms.select([
product in firm.a_lst_product customer.dct_n_trial_up_prod_removed[
and product not in firm.a_lst_product_removed remove_product] = 0
for firm in self.model.a_lst_total_firms print(self.name, remove_product.code, 'affect',
]) customer.name, prod.code)
if not self.dct_cand_alt_supply_up_prod_removed[product]: # print(customer.dct_prod_up_prod_stat)
continue
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 # select based on connection
lst_firm_connect = [] lst_firm_connect = []
if self.is_prf_conn: if self.is_prf_conn:
@ -99,8 +122,8 @@ class FirmAgent(ap.Agent):
if self.is_prf_size: if self.is_prf_size:
lst_size = \ lst_size = \
[size for size in [size for size in
self.dct_cand_alt_supply_up_prod_removed[ self.dct_cand_alt_supply_up_prod_removed[
product].revenue_log] product].revenue_log]
lst_prob = [size / sum(lst_size) lst_prob = [size / sum(lst_size)
for size in lst_size] for size in lst_size]
select_alt_supply = self.model.nprandom.choice( select_alt_supply = self.model.nprandom.choice(
@ -123,10 +146,10 @@ class FirmAgent(ap.Agent):
else: else:
select_alt_supply = \ select_alt_supply = \
self.model.nprandom.choice(lst_firm_connect) self.model.nprandom.choice(lst_firm_connect)
# print( print(
# f"{self.name} selct alt supply for {product.code} " f"{self.name} selct alt supply for {product.code} "
# f"from {select_alt_supply.name}" f"from {select_alt_supply.name}"
# ) )
assert product in select_alt_supply.a_lst_product, \ 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}"
@ -139,17 +162,17 @@ class FirmAgent(ap.Agent):
select_alt_supply.dct_request_prod_from_firm[product] = [ select_alt_supply.dct_request_prod_from_firm[product] = [
self self
] ]
# print( print(
# select_alt_supply.name, 'dct_request_prod_from_firm', { select_alt_supply.name, 'dct_request_prod_from_firm', {
# key.code: [v.name for v in value] key.code: [v.name for v in value]
# for key, value in for key, value in
# select_alt_supply.dct_request_prod_from_firm.items() select_alt_supply.dct_request_prod_from_firm.items()
# }) })
self.dct_n_trial_up_prod_removed[product] += 1 self.dct_n_trial_up_prod_removed[product] += 1
def handle_request(self): 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(): 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(lst_firm) == 0: if len(lst_firm) == 0:
@ -210,6 +233,7 @@ class FirmAgent(ap.Agent):
self.accept_request(select_customer, product) self.accept_request(select_customer, product)
def accept_request(self, down_firm, product): def accept_request(self, down_firm, product):
# para product is the product that self is selling
prod_accept = self.flt_diff_new_conn prod_accept = self.flt_diff_new_conn
if self.model.nprandom.choice([True, False], if self.model.nprandom.choice([True, False],
p=[prod_accept, 1 - prod_accept]): p=[prod_accept, 1 - prod_accept]):
@ -221,11 +245,23 @@ 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_lst_up_product_removed.remove(product) # down_firm.a_lst_up_product_removed.remove(product)
# print(
# f"{self.name} accept {product.code} request " for prod in down_firm.dct_prod_up_prod_stat.keys():
# f"from {down_firm.name}" 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: else:
down_firm.dct_cand_alt_supply_up_prod_removed[product].remove(self) 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 = {} self.dct_request_prod_from_firm = {}
def clean_before_time_step(self): def clean_before_time_step(self):
self.dct_n_trial_up_prod_removed = {} self.dct_n_trial_up_prod_removed = \
self.a_lst_up_product_removed = ap.AgentList(self.model, []) 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): def get_firm_network_node(self):
return self.firm_network.positions[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 code in lst_product for code in self.a_lst_total_products.code
]) ])
self.dct_lst_remove_firm_prod = t_dct 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 # # init output
self.lst_dct_lst_remove_firm_prod = [] # self.lst_dct_lst_remove_firm_prod = []
self.lst_dct_lst_disrupt_firm_prod = [] # self.lst_dct_lst_disrupt_firm_prod = []
# self.dct_ts_dct_a_lst_remove = {}
# set the initial firm product that are removed # set the initial firm product that are removed
for firm, a_lst_product in self.dct_lst_remove_firm_prod.items(): 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, \ 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_lst_product_removed.append(product) firm.a_lst_product_removed.append(product)
firm.dct_prod_up_prod_stat[
product]['status'].append(('R', self.t))
# proactive strategy # proactive strategy
# get all the firm prod affected # get all the firm prod affected
@ -356,20 +360,34 @@ class Model(ap.Model):
def update(self): def update(self):
self.a_lst_total_firms.clean_before_time_step() self.a_lst_total_firms.clean_before_time_step()
# output # # output
self.lst_dct_lst_remove_firm_prod.append( # self.lst_dct_lst_remove_firm_prod.append(
(self.t, self.dct_lst_remove_firm_prod)) # (self.t, self.dct_lst_remove_firm_prod))
self.lst_dct_lst_disrupt_firm_prod.append( # self.lst_dct_lst_disrupt_firm_prod.append(
(self.t, self.dct_lst_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_lst_remove_firm_prod) == 0: # self.dct_lst_remove_firm_prod) == 0:
self.int_stop_times = self.t # self.int_stop_times = self.t
self.stop() # 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): def step(self):
# 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
@ -377,18 +395,33 @@ class Model(ap.Model):
# }) # })
# remove_edge_to_cus_and_cus_up_prod # remove_edge_to_cus_and_cus_up_prod
for firm, a_lst_product in self.dct_lst_remove_firm_prod.items(): for firm in self.a_lst_total_firms:
for product in a_lst_product: for prod in firm.dct_prod_up_prod_stat.keys():
firm.remove_edge_to_cus_remove_cus_up_prod(product) 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): 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_lst_total_firms # shuffle self.a_lst_total_firms
self.a_lst_total_firms = self.a_lst_total_firms.shuffle() self.a_lst_total_firms = self.a_lst_total_firms.shuffle()
for firm in self.a_lst_total_firms: for firm in self.a_lst_total_firms:
if len(firm.a_lst_up_product_removed) > 0: # if len(firm.a_lst_up_product_removed) > 0:
firm.seek_alt_supply() # 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 # handle_request
# shuffle self.a_lst_total_firms # shuffle self.a_lst_total_firms
@ -402,35 +435,43 @@ class Model(ap.Model):
# do not use: # do not use:
# self.a_lst_total_firms.dct_request_prod_from_firm = {} why? # 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 a_lst_product_disrupted / a_lst_product_removed
# update dct_lst_disrupt_firm_prod / dct_lst_remove_firm_prod # update dct_lst_disrupt_firm_prod / dct_lst_remove_firm_prod
self.dct_lst_remove_firm_prod = {} # self.dct_lst_remove_firm_prod = {}
self.dct_lst_disrupt_firm_prod = {} # self.dct_lst_disrupt_firm_prod = {}
for firm in self.a_lst_total_firms: for firm in self.a_lst_total_firms:
if len(firm.a_lst_up_product_removed) > 0: # if len(firm.a_lst_up_product_removed) > 0:
# print(firm.name, 'a_lst_up_product_removed', [ # print(firm.name, 'a_lst_up_product_removed', [
# product.code for product in firm.a_lst_up_product_removed # product.code for product in firm.a_lst_up_product_removed
# ]) # ])
for product in firm.a_lst_product: for product in firm.dct_prod_up_prod_stat.keys():
n_up_product_removed = 0 status = firm.dct_prod_up_prod_stat[product]['status'][-1][0]
for up_product_removed in firm.a_lst_up_product_removed: if status == 'D':
if product in up_product_removed.a_successors(): print(firm.name, 'disrupted product: ', product.code)
n_up_product_removed += 1 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: if n_up_product_removed == 0:
continue continue
else: else:
# update a_lst_product_disrupted # # update a_lst_product_disrupted
# update dct_lst_disrupt_firm_prod # # update dct_lst_disrupt_firm_prod
if product not in firm.a_lst_product_disrupted: # if product not in firm.a_lst_product_disrupted:
firm.a_lst_product_disrupted.append(product) # firm.a_lst_product_disrupted.append(product)
if firm in self.dct_lst_disrupt_firm_prod.keys(): # if firm in self.dct_lst_disrupt_firm_prod.keys():
self.dct_lst_disrupt_firm_prod[firm].append( # self.dct_lst_disrupt_firm_prod[firm].append(
product) # product)
else: # else:
self.dct_lst_disrupt_firm_prod[ # self.dct_lst_disrupt_firm_prod[
firm] = ap.AgentList( # firm] = ap.AgentList(
self.model, [product]) # self.model, [product])
# update a_lst_product_removed # update a_lst_product_removed
# update dct_list_remove_firm_prod # update dct_list_remove_firm_prod
# mark disrupted firm as removed based conditionally # mark disrupted firm as removed based conditionally
@ -457,13 +498,20 @@ class Model(ap.Model):
p=[prob_remove, p=[prob_remove,
1 - prob_remove]): 1 - prob_remove]):
firm.a_lst_product_removed.append(product) firm.a_lst_product_removed.append(product)
if firm in self.dct_lst_remove_firm_prod.keys(): # if firm in self.dct_lst_remove_firm_prod.keys():
self.dct_lst_remove_firm_prod[firm].append( # self.dct_lst_remove_firm_prod[firm].append(
product) # product)
else: # else:
self.dct_lst_remove_firm_prod[ # self.dct_lst_remove_firm_prod[
firm] = ap.AgentList( # firm] = ap.AgentList(
self.model, [product]) # 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( # print(
# 'dct_list_remove_firm_prod', { # 'dct_list_remove_firm_prod', {
@ -472,7 +520,7 @@ class Model(ap.Model):
# }) # })
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.lst_dct_lst_remove_firm_prod: # for t, dct in self.lst_dct_lst_remove_firm_prod:
# for firm, a_lst_product in dct.items(): # for firm, a_lst_product in dct.items():
@ -484,35 +532,35 @@ class Model(ap.Model):
# for product in a_lst_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.lst_dct_lst_disrupt_firm_prod: # for t, dct in self.lst_dct_lst_disrupt_firm_prod:
for firm, a_lst_product in dct.items(): # for firm, a_lst_product in dct.items():
for product in a_lst_product: # for product in a_lst_product:
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,
ts=t, # ts=t,
is_disrupted=True) # is_disrupted=True)
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.lst_dct_lst_remove_firm_prod: # for t, dct in self.lst_dct_lst_remove_firm_prod:
for firm, a_lst_product in dct.items(): # for firm, a_lst_product in dct.items():
for product in a_lst_product: # for product in a_lst_product:
# only firm disrupted can be removed theoretically # # only firm disrupted can be removed theoretically
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,
Result.id_product == product.code) # Result.id_product == product.code)
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 = 1 # self.sample.is_done_flag = 1
self.sample.computer_name = platform.node() # 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()
def draw_network(self): def draw_network(self):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt

View File

@ -266,6 +266,38 @@
" )\n", " )\n",
"lst_choose_firm" "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": { "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 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