病毒扩散程序怎么写

时间:2025-01-26 10:28:47 单机游戏

编写病毒扩散程序需要考虑多个方面,包括病毒的传播机制、人群的移动和状态变化、以及数据的可视化等。以下是一个简单的Python示例,用于模拟病毒在人群中的扩散过程:

```python

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

定义人群类

class Person:

def __init__(self, x, y, state=0):

self.x = x

self.y = y

self.state = state

定义人群集合

class People:

def __init__(self, count=1000, first_infected_count=3):

self.count = count

self.first_infected_count = first_infected_count

self.people = self.init()

def init(self):

self._people = np.random.normal(0, 100, (self.count, 2))

self.reset()

def reset(self):

初始化人群状态

self.people[:, 2] = np.random.choice([0, 1, 2, 3, 4, 5], size=self.count)

def move(self, direction):

定义移动方向

dx, dy = direction

new_x, new_y = self.people[:, 0] + dx, self.people[:, 1] + dy

检查新位置是否有效

if 0 <= new_x < 100 and 0 <= new_y < 100:

self.people[:, 0], self.people[:, 1] = new_x, new_y

def infect(self, person, virus):

感染逻辑

if person.state == 0 and np.random.random() < virus.spread_rate:

person.state = 1 疑似

virus.infected_count += 1

定义病毒类

class Virus:

def __init__(self, spread_rate=0.8, infection_radius=5):

self.spread_rate = spread_rate

self.infection_radius = infection_radius

self.infected_count = 0

def spread(self, people):

扩散逻辑

for i in range(people.count):

person = people.people[i]

if person.state == 1:

for j in range(people.count):

if i != j and np.linalg.norm(np.array([person.x, person.y]) - np.array([people.people[j], people.people[j]])) < self.infection_radius:

people.infect(people.people[j], self)

初始化人群和病毒

people = People()

virus = Virus()

模拟病毒扩散

fig, ax = plt.subplots()

scatter = ax.scatter(people.people[:, 0], people.people[:, 1], c=people.people[:, 2])

def update(frame):

global virus, people

virus.spread(people)

for i in range(people.count):

person = people.people[i]

if person.state == 1:

scatter.set_offsets(np.c_[person.x, person.y])

return scatter,

ani = FuncAnimation(fig, update, frames=range(100), interval=50, blit=True)

plt.show()

```

代码说明:

Person类 :表示一个人,包含坐标和状态。

People类:

表示人群,包含人群的坐标和状态,并提供初始化、移动和感染方法。

Virus类:

表示病毒,包含传播率和感染半径,并提供扩散方法。

模拟过程

初始化人群和病毒。

使用`matplotlib`的`FuncAnimation`进行动画模拟,每帧更新病毒扩散和人群状态。

这个示例是一个简单的模拟,实际应用中可能需要根据具体需求进行调整和扩展。