本章借助matplotlib
包,模拟疫情传播,有两种思路:
面向对象的方式,每个人为一个独立对象,算法:
算法逻辑非常简单,但是可以看到会嵌套多次循环,时间复杂度为: O ( n 2 ) O(n^2) O(n2)
import numpy as np
import matplotlib.pyplot as plt
# 地图宽度
width = 100
# 总人口
pop = 2000
# 初始病人数量
n = 10
# 感染半径
sd = 10
# 感染几率 50%
sr = 0.5
# 人
class People(object):
def __init__(self):
# 随机坐标
self.x = np.random.rand() * width
self.y = np.random.rand() * width
self.loc = np.array([self.x, self.y])
self.color = 'g'
# 随机运动
def move(self):
self.x += np.random.randn()
self.y += np.random.randn()
# 人群
all_people = np.array([People() for i in range(pop)])
# 初始化患病人群
sick_people = np.random.choice(all_people, size=n, replace=False)
for p in sick_people:
p.color = "r"
# 病毒感染函数
def affect(all_people):
sick_people = []
healthy_people = []
n = 0
for p in all_people:
if p.color == "r":
sick_people.append(p)
n += 1
if p.color == "g":
healthy_people.append(p)
for sp in sick_people:
for hp in healthy_people:
dist = np.linalg.norm(sp.loc - hp.loc)
rad = np.random.rand()
if hp.color == "g" and dist <= sd and rad < sr:
hp.color = "r"
n += 1
return n
使用matplotlib
互交模式,动态显示
plt.ion()
# 模拟
while n < pop:
plt.clf()
update(all_people)
n = affect(all_people)
plt.scatter([p.x for p in all_people], [p.y for p in all_people], c=[p.color for p in all_people], s=3)
plt.axis([0, width, 0, width])
plt.pause(0.5)
print("总人数:{},传染人数:{}".format(pop, n))
plt.ioff()
plt.show()
总人数:1000,传染人数:150
总人数:1000,传染人数:585
总人数:1000,传染人数:875
总人数:1000,传染人数:984
总人数:1000,传染人数:1000
借助numpy
,可以非常快速的处理矩阵运算,特点:
时间复杂度为: O ( n ) O(n) O(n)
import numpy as np
import matplotlib.pyplot as plt
class VirusSimulator(object):
def __init__(self):
# 地图宽度
self.width = 100
# 总人口
self.pop = 5000
# 初始病人数量
self.first_patients = 10
# 感染半径
self.infection_radius = 5
# 感染几率 50%
self.infection_potential = 0.5
# 人群:横坐标、纵坐标
self.locations = np.random.randn(self.pop, 2) * self.width
# 状态:(g-正常、r-感染)
self.status = np.array(["g"] * self.pop)
# 初始化感染群
self.initPatients()
# 更新人群位置
def move(self):
self.locations += np.random.randn(self.pop, 2)
# 初始化患病人群
def initPatients(self):
for i in np.random.randint(self.pop, size=self.first_patients):
if self.status[i] == "g":
self.status[i] = "r"
# 统计感染人群
@property
def patients(self):
return self.locations[self.status == "r"]
# 统计感染人数
@property
def patients_num(self):
return self.status[self.status == "r"].size
# 传染函数
def affect(self):
for ip in self.patients:
distances = np.sqrt(np.sum(np.asarray(ip - self.locations)**2, axis=1))
self.status[distances < self.infection_radius] = "r"
# 显示函数
def display(self):
current_patient_num = self.patients_num
print("总人数:{},传染人数:{}".format(self.pop, current_patient_num))
plt.ion()
while current_patient_num < self.pop:
plt.clf()
plt.scatter(self.locations[:, 0], self.locations[:, 1], c=self.status, s=1)
plt.axis([-self.width, self.width, -self.width, self.width])
self.move()
self.affect()
current_patient_num = self.patients_num
print("总人数:{},传染人数:{}".format(self.pop, current_patient_num))
plt.pause(0.5)
plt.ioff()
plt.show()
if __name__ == "__main__":
vs = VirusSimulator()
vs.display()
运动
简单的生成一个随机向量矩阵,大小和原来的坐标矩阵一致,然后相加,即可达到随机运动的效果。
# 更新人群位置
def move(self):
self.locations += np.random.randn(self.pop, 2)
装饰器
Python内置的@property
装饰器就是负责把一个方法变成属性调用
# 统计感染人群
@property
def patients(self):
return self.locations[self.status == "r"]
# 统计感染人数
@property
def patients_num(self):
return self.status[self.status == "r"].size
感染函数
distances
potential
k
b
k * b
的邻居标记为感染 # 传染函数
def affect(self):
for ip in self.patients:
distances = np.sqrt(np.sum(np.asarray(ip - self.locations)**2, axis=1))
potential = np.random.rand(self.pop)
# 小于传染距离的矩阵
k = distances < self.infection_radius
# 达到传染几率的矩阵
b = potential < self.infection_potential
# 既小于传染距离又达到传染几率的人群
self.status[k * b] = "r"
距离算法:
distances = np.sqrt(np.sum(np.asarray(ip - self.locations)**2, axis=1))
实际上可以分解为
l = np.asarray(ip - self.locations)
其中ip
为单一的点,self.locations
为数组,结果也为数组,大小和self.locations
一样。
更进一步,得到每个点的差的乘积
l = np.asarray(ip - self.locations)**2
乘积相加,但是这样只有一个数字,
s = np.sum(np.array(ip - self.locations)**2)
想要得到矩阵,需要控制参数axis
# axis=1,表示沿着x轴相加,横向
l = np.sum(np.array(p - locations)**2,axis=1)
# axis=1,表示沿着y轴相加,竖向
l = np.sum(np.array(p - locations)**2,axis=0)
最后再对每一个元素开方,得到结果