add comments

This commit is contained in:
HaoYizhi 2023-08-22 23:22:30 -04:00
parent 1d66d8bb4e
commit b84ab810d0
3 changed files with 31 additions and 28 deletions

28
firm.py
View File

@ -6,7 +6,7 @@ class FirmAgent(ap.Agent):
self.firm_network = self.model.firm_network
self.product_network = self.model.product_network
# self para
# self parameter
self.code = code
self.name = name
self.type_region = type_region
@ -14,7 +14,7 @@ class FirmAgent(ap.Agent):
self.dct_prod_up_prod_stat = {}
self.dct_prod_capacity = {}
# para in trial
# parameter in trial
self.dct_n_trial_up_prod_disrupted = {}
self.dct_cand_alt_supp_up_prod_disrupted = {}
self.dct_request_prod_from_firm = {}
@ -26,14 +26,14 @@ class FirmAgent(ap.Agent):
self.flt_cap_limit_level = float(self.p.cap_limit_level)
self.flt_diff_new_conn = float(self.p.diff_new_conn)
# init size_stat (self para)
# initialize size_stat (self parameter)
# (size, time step)
self.size_stat.append((revenue_log, 0))
# init dct_prod_up_prod_stat (self para)
# init dct_prod_up_prod_stat (self parameter)
for prod in a_lst_product:
self.dct_prod_up_prod_stat[prod] = {
# (Normal / Disrupted / Removed, time step)
# status: (Normal / Disrupted / Removed, time step)
'p_stat': [('N', 0)],
# supply for each component and respective disrupted supplier
# set_disrupt_firm is refreshed to empty at each update
@ -43,9 +43,9 @@ class FirmAgent(ap.Agent):
# Note: do not use fromkeys as it's a shallow copy
}
# init extra capacity (self para)
# initialize extra capacity (self parameter)
for product in a_lst_product:
# init extra capacity based on discrete uniform distribution
# initialize extra capacity based on discrete uniform distribution
assert self.str_cap_limit_prob_type in ['uniform', 'normal'], \
"cap_limit_prob_type other than uniform, normal"
if self.str_cap_limit_prob_type == 'uniform':
@ -63,7 +63,7 @@ class FirmAgent(ap.Agent):
self.dct_prod_capacity[product] = extra_cap
def remove_edge_to_cus(self, disrupted_prod):
# para disrupted_prod is the product that self got disrupted
# parameter disrupted_prod is the product that self got disrupted
lst_out_edge = list(
self.firm_network.graph.out_edges(
self.firm_network.positions[self], keys=True, data='Product'))
@ -84,8 +84,8 @@ class FirmAgent(ap.Agent):
self.firm_network.graph.remove_edge(n1, n2, key)
def disrupt_cus_prod(self, prod, disrupted_up_prod):
# para prod is the product that has disrupted_up_prod
# para disrupted_up_prod is the product that
# parameter prod is the product that has disrupted_up_prod
# parameter disrupted_up_prod is the product that
# self's component exists disrupted supplier
num_lost = \
len(self.dct_prod_up_prod_stat[prod]['s_stat']
@ -101,6 +101,8 @@ class FirmAgent(ap.Agent):
[firm.size_stat[-1][0] for firm in self.model.a_lst_total_firms]
std_size = (self.size_stat[-1][0] - min(lst_size) + 1) \
/ (max(lst_size) - min(lst_size) + 1)
# calculate probability of disruption
prob_disrupt = 1 - std_size * (1 - lost_percent)
if self.model.nprandom.choice([True, False],
p=[prob_disrupt,
@ -117,7 +119,7 @@ class FirmAgent(ap.Agent):
# f"disrupted supplier of {disrupted_up_prod.code}")
def seek_alt_supply(self, product):
# para product is the product that self is seeking
# parameter product is the product that self is seeking
# print(f"{self.name} seek alt supply for {product.code}")
if self.dct_n_trial_up_prod_disrupted[
product] <= self.model.int_n_max_trial:
@ -258,8 +260,8 @@ class FirmAgent(ap.Agent):
# )
def accept_request(self, down_firm, product):
# para product is the product that self is selling
# connected firm has no probability
# parameter product is the product that self is selling
# connected firm has no probability for accepting request
node_self = self.get_firm_network_node()
node_d_firm = down_firm.get_firm_network_node()
if self.model.firm_network.graph.has_edge(node_self, node_d_firm) or \

View File

@ -10,7 +10,7 @@ import json
class Model(ap.Model):
def setup(self):
# self para
# self parameter
self.sample = self.p.sample
self.int_stop_ts = 0
self.int_n_iter = int(self.p.n_iter)
@ -27,11 +27,11 @@ class Model(ap.Model):
self.remove_t = int(self.p.remove_t)
self.int_netw_prf_n = int(self.p.netw_prf_n)
# init graph bom
# initialize graph bom
G_bom = nx.adjacency_graph(json.loads(self.p.g_bom))
self.product_network = ap.Network(self, G_bom)
# init graph firm
# initialize graph firm
Firm = pd.read_csv("Firm_amended.csv")
Firm['Code'] = Firm['Code'].astype('string')
Firm.fillna(0, inplace=True)
@ -49,7 +49,7 @@ class Model(ap.Model):
firm_labels_dict[code] = Firm_attr.loc[code].to_dict()
nx.set_node_attributes(G_Firm, firm_labels_dict)
# init graph firm prod
# initialize graph firm prod
Firm_Prod = pd.read_csv("Firm_amended.csv")
Firm_Prod.fillna(0, inplace=True)
firm_prod = pd.DataFrame({'bool': Firm_Prod.loc[:, '1':].stack()})
@ -122,11 +122,12 @@ class Model(ap.Model):
# nx.to_pandas_adjacency(G_Firm).to_csv('adj_g_firm.csv')
# nx.to_pandas_adjacency(G_FirmProd).to_csv('adj_g_firm_prod.csv')
# unconnected node
# connect unconnected nodes
for node in nx.nodes(G_Firm):
if G_Firm.degree(node) == 0:
for product_code in G_Firm.nodes[node]['Product_Code']:
# unconnect node does not have possible suppliers
# unconnected node does not have possible suppliers,
# therefore find possible customer instead
# current node in graph firm prod
current_node = \
[n for n, v in G_FirmProd.nodes(data=True)
@ -135,10 +136,10 @@ class Model(ap.Model):
lst_succ_product_code = list(
G_bom.successors(product_code))
# different from for different types of product,
# different from: for different types of product,
# finding a common supplier (the logic above),
# for different types of product,
# finding a custormer for each product
# instead: for different types of product,
# finding a customer for each product
for succ_product_code in lst_succ_product_code:
# for each product successor (finished product)
# the firm sells to,
@ -187,14 +188,14 @@ class Model(ap.Model):
# nx.draw(G_FirmProd)
# plt.show()
# init product
# initialize product
for ag_node, attr in self.product_network.graph.nodes(data=True):
product = ProductAgent(self, code=ag_node.label, name=attr['Name'])
self.product_network.add_agents([product], [ag_node])
self.a_lst_total_products = ap.AgentList(self,
self.product_network.agents)
# init firm
# initialize firm
for ag_node, attr in self.firm_network.graph.nodes(data=True):
firm_agent = FirmAgent(
self,
@ -210,7 +211,7 @@ class Model(ap.Model):
self.firm_network.add_agents([firm_agent], [ag_node])
self.a_lst_total_firms = ap.AgentList(self, self.firm_network.agents)
# init dct_lst_init_disrupt_firm_prod (from string to agent)
# initialize dct_lst_init_disrupt_firm_prod (from string to agent)
t_dct = {}
for firm_code, lst_product in \
self.dct_lst_init_disrupt_firm_prod.items():
@ -368,7 +369,7 @@ class Model(ap.Model):
firm.dct_prod_up_prod_stat[
prod]['p_stat'].append(('R', self.t))
# stop simulation if any firm still in disrupted except inital removal
# stop simulation if any firm still in disrupted except initial removal
if self.t > 0:
for firm in self.a_lst_total_firms:
for prod in firm.dct_prod_up_prod_stat.keys():
@ -443,8 +444,6 @@ class Model(ap.Model):
# reset dct_request_prod_from_firm
self.a_lst_total_firms.clean_before_trial()
# do not use:
# self.a_lst_total_firms.dct_request_prod_from_firm = {} why?
def end(self):
# print('/' * 20, 'output', '/' * 20)

View File

@ -9,6 +9,7 @@ class ProductAgent(ap.Agent):
self.name = name
def a_successors(self):
# find successors of a product, return in AgentList (ProductAgent)
nodes = self.product_network.graph.successors(
self.product_network.positions[self])
return ap.AgentList(
@ -16,6 +17,7 @@ class ProductAgent(ap.Agent):
[ap.AgentIter(self.model, node).to_list()[0] for node in nodes])
def a_predecessors(self):
# find predecessors of a product, return in AgentList (ProductAgent)
nodes = self.product_network.graph.predecessors(
self.product_network.positions[self])
return ap.AgentList(