使用 Reynolds 提出的 Boids 模型来模拟鸟群行为。Reynolds 的 Boids 模型基于三条简单的规则:
1. **分离 (Separation)**:避免与其他鸟过于接近。
2. **对齐 (Alignment)**:朝向邻居鸟的方向飞行。
3. **聚合 (Cohesion)**:飞向邻居鸟的平均位置。
我们还将添加驱散效果(scatter effect),以研究局部扰动对鸟群的影响。为了可视化鸟群的行为变化,我们将使用 `matplotlib` 来绘制每只鸟的位置和飞行方向。
### 完整代码示例【教科书版】
"""
boids.py
Boids模型的一种实现
编写者:Mahesh Venkitachalam
"""
import argparse
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.spatial.distance import squareform, pdist
from numpy.linalg import norm
width, height = 640, 480
class Boids:
"""表示全体行为模拟的类"""
def __init__(self, N):
"""初始化群体行为模拟"""
# 初始化位置和速度
self.pos = [width/2.0, height/2.0] +10*np.random.rand(2*N).reshape(N, 2)
# 归一化随机速度
angles = 2*math.pi*np.random.rand(N)
self.vel = np.array(list(zip(np.cos(angles), np.sin(angles))))
self.N = N
# 个体间的最小距离
self.minDist = 25.0
# 应用规则导致的最大速度变化量
self.maxRuleVel = 0.03
# 最大速度
self.maxVel = 2.0
def tick(self, frameNum, pts, head):
"""在每个时间步中更新模拟"""
# 应用规则
self.vel += self.applyRules()
self.limit(self.vel, self.maxVel)
self.pos += self.vel
self.applyBC()
# 更新数据
pts.set_data(self.pos.reshape(2*self.N)[::2],
self.pos.reshape(2*self.N)[1::2])
vec = self.pos + 10*self.vel/self.maxVel
head.set_data(vec.reshape(2*self.N)[::2],
vec.reshape(2*self.N)[1::2])
def limitVec(self, vec, maxVal):
"""限制二维向量的长度"""
mag = norm(vec)
if mag > maxVal:
vec[0], vec[1] = vec[0]*maxVal/mag, vec[1]*maxVal/mag
def limit(self, X, maxVal):
"""对数组X中二维向量的长度进行限制,使其不超过maxValue """
for vec in X: