Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize isolation Simulation by Python based on Agent

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces how to achieve isolation simulation based on Agent Python, the content is very detailed, interested friends can refer to, hope to be helpful to you.

I will introduce you to the power of using Agent-based models to understand complex phenomena. To do this, we will use some Python, sociological case studies and Schelling models.

1. Case analysis

If you look at the racial distribution in multi-ethnic mixed cities, you will be surprised by the incredible apartheid. For example, here is a map of New York City marked by race and color by the U.S. Census Bureau (US Census). Apartheid is clearly visible.

From this phenomenon, many people will think that people are intolerant and do not want to live next to other races. However, if you look further, you will find subtle differences. Thomas Schelling (Thomas Schelling), the 2005 Nobel laureate in economics, was very interested in this aspect in the 1970s, and established an Agent-based model-"Schelling isolation model" to explain this phenomenon. With this extremely simple model, Schelling will tell us that what we see in the macro is not what we do in the micro (What's going down).

We will use the Schelling model to simulate some simulations to deeply understand the isolation phenomenon.

2. Schelling isolation model: setting and definition

The Agent-based model requires three parameters: 1) Agents,2) behavior (rules) and 3) overall level (aggregate level) evaluation. In the Schelling model, Agents is a citizen, the behavior is based on the similarity ratio (similarity ratio), and the overall evaluation is the similarity ratio.

Suppose there are n races in the city. We use a unique color to identify them, and a grid to represent the city, and each cell is a room. It is either an empty house or a resident, and the number is 1. If the house is empty, we use a white sign. If there is a resident, we use the color of the person's population to identify it. We define the houses around everyone (up and down, left and right, left and right, left, lower and right) as neighbors.

The aim of Schelling is to test what happens when residents are more likely to choose neighbors of the same race (or even multiple races). If the proportion of neighbors of the same race rises to a certain threshold (called the similarity threshold (Similarity Threshold)), then we think the person is satisfied (satisfied). If not, I am not satisfied.

The simulation of Schelling is as follows. First of all, we randomly assign people to the city and leave some houses vacant. For each resident, we will check whether he or she is satisfied. If we are satisfied, we will do nothing. But if we are not satisfied, we will assign him to an empty house. After several iterations of the simulation, we will observe the final ethnic distribution.

3. Python implementation of Schelling model

As early as the 1970s, Schelling completed his simulation on paper with pencils and coins. We now use Python to complete the same simulation.

In order to simulate, we first import some necessary libraries. With the exception of Matplotlib, all libraries are installed by default with Python.

Python

Import matplotlib.pyplot as plt

Import itertools

Import random

Import copy

Next, define a class called Schelling, which involves six parameters: width and height of the city, proportion of empty houses, similarity threshold, number of iterations, and number of races. We define four methods in this class: populate,is_unsatisfied,update,move_to_empty, and plot).

Python

Class Schelling:

Def _ init__ (self, width, height, empty_ratio, similarity_threshold, n_iterations, races = 2):

Self.width = width

Self.height = height

Self.races = races

Self.empty_ratio = empty_ratio

Self.similarity_threshold = similarity_threshold

Self.n_iterations = n_iterations

Self.empty_houses = []

Self.agents = {}

Def populate (self):

....

Def is_unsatisfied (self, x, y):

....

Def update (self):

....

Def move_to_empty (self, x, y):

....

Def plot (self):

....

The poplate method is used at the beginning of the simulation, in which residents are randomly assigned to the grid.

Python

Def populate (self):

Self.all_houses = list (itertools.product (range (self.width), range (self.height)

Random.shuffle (self.all_houses)

Self.n_empty = int (self.empty_ratio * len (self.all_houses))

Self.empty_houses = self.all_houses [: self.n_empty]

Self.remaining_houses = self.all_ gifts [self.n _ empty:]

Houses_by_race = [self.remaining_ arrangements [I:: self.races] for i in range (self.races)]

For i in range (self.races):

# create an agent for each race

Self.agents = dict (

Self.agents.items () +

Dict (zip (houses_by_race [I], [item1] * len (houses_by_ Race [I])) .items ()

The is_unsatisfied method takes the (x, y) coordinates of the house as the incoming parameter, looks at the proportion of neighbors of the same group, and returns True if it is higher than the ideal threshold (happiness threshold), otherwise it returns False.

Python

Def is_unsatisfied (self, x, y):

Race = self.agents [(xQuery)]

Count_similar = 0

Count_different = 0

If x > 0 and y > 0 and (Xmuri 1, ymai 1) not in self.empty_houses:

If self.agents [(xmur1, ymur1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If y > 0 and (XQuery ymur1) not in self.empty_houses:

If self.agents [(xmaiymur1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If x

< (self.width-1) and y >

0 and (xylene 1) not in self.empty_houses:

If self.agents [(xylene 1 ~ ymur1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If x > 0 and (XMY 1pm y) not in self.empty_houses:

If self.agents [(xMel 1Query y)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If x

< (self.width-1) and (x+1,y) not in self.empty_houses: if self.agents[(x+1,y)] == race: count_similar += 1 else: count_different += 1 if x >

0 and y

< (self.height-1) and (x-1,y+1) not in self.empty_houses: if self.agents[(x-1,y+1)] == race: count_similar += 1 else: count_different += 1 if x >

0 and y

< (self.height-1) and (x,y+1) not in self.empty_houses: if self.agents[(x,y+1)] == race: count_similar += 1 else: count_different += 1 if x < (self.width-1) and y < (self.height-1) and (x+1,y+1) not in self.empty_houses: if self.agents[(x+1,y+1)] == race: count_similar += 1 else: count_different += 1 if (count_similar+count_different) == 0: return False else: return float(count_similar)/(count_similar+count_different) < self.happy_threshold update 方法将查看网格上的居民是否尚未满意,如果尚未满意,将随机把此人分配到空房子中。并模拟 n_iterations 次。 Python def update(self): for i in range(self.n_iterations): self.old_agents = copy.deepcopy(self.agents) n_changes = 0 for agent in self.old_agents: if self.is_unhappy(agent[0], agent[1]): agent_race = self.agents[agent] empty_house = random.choice(self.empty_houses) self.agents[empty_house] = agent_race del self.agents[agent] self.empty_houses.remove(empty_house) self.empty_houses.append(agent) n_changes += 1 print n_changes if n_changes == 0: break move_to_empty 方法把房子坐标(x, y)作为传入参数,并将 (x, y) 房间内的居民迁入空房子。这个方法被 update 方法调用,会把尚不满意的人迁入空房子。 Python def move_to_empty(self, x, y): race = self.agents[(x,y)] empty_house = random.choice(self.empty_houses) self.updated_agents[empty_house] = race del self.updated_agents[(x, y)] self.empty_houses.remove(empty_house) self.empty_houses.append((x, y)) plot 方法用来绘制整个城市和居民。我们随时可以调用这个方法来了解城市的居民分布。这个方法有两个传入参数:title 和 file_name。 Python def plot(self, title, file_name): fig, ax = plt.subplots() # 如果要进行超过 7 种颜色的仿真,你应该相应地进行设置 agent_colors = {1:'b', 2:'r', 3:'g', 4:'c', 5:'m', 6:'y', 7:'k'} for agent in self.agents: ax.scatter(agent[0]+0.5, agent[1]+0.5, color=agent_colors[self.agents[agent]]) ax.set_title(title, fontsize=10, fontweight='bold') ax.set_xlim([0, self.width]) ax.set_ylim([0, self.height]) ax.set_xticks([]) ax.set_yticks([]) plt.savefig(file_name) 4. 仿真 现在我们实现了 Schelling 类,可以模拟仿真并绘制结果。我们会按照下面的需求(characteristics)进行三次仿真: 宽 = 50,而高 = 50(包含 2500 间房子) 30% 的空房子 相似性阈值 = 30%(针对仿真 1),相似性阈值 = 50%(针对仿真 2),相似性阈值 = 80%(针对仿真 3) 最大迭代数 = 500 种族数量 = 2 创建并"填充"城市。 Python schelling_1 = Schelling(50, 50, 0.3, 0.3, 500, 2) schelling_1.populate() schelling_2 = Schelling(50, 50, 0.3, 0.5, 500, 2) schelling_2.populate() schelling_3 = Schelling(50, 50, 0.3, 0.8, 500, 2) schelling_3.populate() 接下来,我们绘制初始阶段的城市。注意,相似性阈值在城市的初始状态不起作用。 Python schelling_1_1.plot('Schelling Model with 2 colors: Initial State', 'schelling_2_initial.png') 下面我们运行 update 方法,绘制每个相似性阈值的最终分布。 Python schelling_1.update() schelling_2.update() schelling_3.update() schelling_1.plot('Schelling Model with 2 colors: Final State with Similarity Threshold 30%', 'schelling_2_30_final.png') schelling_2.plot('Schelling Model with 2 colors: Final State with Similarity Threshold 50%', 'schelling_2_50_final.png') schelling_3.plot('Schelling Model with 2 colors: Final State with Similarity Threshold 80%', 'schelling_2_80_final.png') 我们发现相似性阈值越高,城市的隔离度就越高。此外,我们还会发现即便相似性阈值很小,城市依旧会产生隔离。换言之,即使居民非常包容(tolerant)(相当于相似性阈值很小),还是会以隔离告终。我们可以总结出:宏观所见并非微观所为。 5. 测量隔离 以上仿真,我们只通过可视化来确认隔离发生。然而,我们却没有对隔离的计算进行定量评估。本节我们会定义这个评估标准,我们也会模拟一些仿真来确定理想阈值和隔离程度的关系。 首先在 Schelling 类中添加 calculate_similarity 方法。这个方法会计算每个 Agent 的相似性并得出均值。我们会用平均相似比评估隔离程度。 Python def calculate_similarity(self): similarity = [] for agent in self.agents: count_similar = 0 count_different = 0 x = agent[0] y = agent[1] race = self.agents[(x,y)] if x >

0 and y > 0 and (Xmur1, ymur1) not in self.empty_houses:

If self.agents [(xmur1, ymur1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If y > 0 and (XQuery ymur1) not in self.empty_houses:

If self.agents [(xmaiymur1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If x

< (self.width-1) and y >

0 and (xylene 1) not in self.empty_houses:

If self.agents [(xylene 1 ~ ymur1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If x > 0 and (XMY 1pm y) not in self.empty_houses:

If self.agents [(xMel 1Query y)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If x

< (self.width-1) and (x+1,y) not in self.empty_houses: if self.agents[(x+1,y)] == race: count_similar += 1 else: count_different += 1 if x >

0 and y

< (self.height-1) and (x-1,y+1) not in self.empty_houses: if self.agents[(x-1,y+1)] == race: count_similar += 1 else: count_different += 1 if x >

0 and y < (self.height-1) and (Xmeme Yellow1) not in self.empty_houses:

If self.agents [(xQuery Yicheng 1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

If x < (self.width-1) and y < (self.height-1) and (Xero1djin1) not in self.empty_houses:

If self.agents [(xylene 1)] = = race:

Count_similar + = 1

Else:

Count_different + = 1

Try:

Similarity.append (float (count_similar) / (count_similar+count_different))

Except:

Similarity.append (1)

Return sum (similarity) / len (similarity)

Next, we calculate the average similarity ratio of each similarity threshold and draw the relationship between the similarity threshold and the similarity ratio.

Python

Similarity_threshold_ratio = {}

For i in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]:

Schelling = Schelling (50,50,0.3,500,2)

Schelling.populate ()

Schelling.update ()

Similarity_threshold_ ratio [I] = schelling.calculate_similarity ()

Fig, ax = plt.subplots ()

Plt.plot (similarity_threshold_ratio.keys (), similarity_threshold_ratio.values (), 'ro')

Ax.set_title ('Similarity Threshold vs. Mean Similarity Ratio', fontsize=15, fontweight='bold')

Ax.set_xlim ([0,1])

Ax.set_ylim ([0,1.1])

Ax.set_xlabel ("Similarity Threshold")

Ax.set_ylabel ("Mean Similarity Ratio")

Plt.savefig ('schelling_segregation_measure.png')

On the Agent-based Python is how to achieve isolation simulation is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report