“Flocking”算法是一种基于行为的模型,主要被用来模拟动物群体的行为,如鸟群或鱼群。它在1986年由计算机图形学家Craig Reynolds首次提出。
1. 凝聚(Cohesion):每个个体会试图靠近并保持在周围个体的平均位置附近。
注:独立的个体逐渐加入到群体
2.对齐(Alignment):每个个体会试图将自己的速度和方向与周围个体的平均速度和方向相匹配。
注:个体与群体的航向保持一致,不要脱离
3.分离(Separation):每个个体都会尽量避免与周围其他个体过于接近,以防止碰撞。
注:避免群体内的个体相互碰撞
假设我们有N个智能体(或称个体、实体),每个智能体i的位置用二维向量
表示,速度用二维向量
表示。
下面是这三个规则对应的计算公式:
1.分离(Separation):智能体i会计算它与其他所有智能体的距离,然后选择一个向量,使其远离距离过近的智能体。这个分离向量
可以通过以下公式得到:
这个公式的分子表示智能体i与其他智能体j之间的距离向量,分母是智能体i与智能体j之间的距离的平方。这个公式实际上是在对所有的智能体j求和,但是排除了i自己(j≠i)。
2.对齐(Alignment):智能体i会计算所有智能体的平均速度(排除了i自己),然后尝试对齐这个速度。这个对齐向量可以通过以下公式得到:
这个公式的分子是所有智能体(除了i自己)速度向量的和,分母是智能体的总数减一。
3.凝聚(Cohesion):智能体i会计算所有智能体的平均位置(排除了i自己),然后尝试移动到这个位置。这个凝聚向量可以通过以下公式得到:
这个公式的分子是所有智能体(除了i自己)位置向量的和除以智能体的总数减一,然后减去智能体i的位置向量。
然后,我们就可以根据这三个向量来更新智能体i的速度和位置了。新的速度向量可以通过以下公式得到:
这里,是权重,它们决定了分离、对齐和凝聚规则对速度更新的影响程度。然后,我们可以根据新的速度向量来更新智能体i的位置:
其中,
是时间步长。
这就是Flocking模型的基本数学描述。需要注意的是,为了防止智能体速度过大,我们通常会给速度设置一个上限。另外,分离、对齐和凝聚的规则通常只考虑邻近的智能体,即距离智能体i一定范围内的其他智能体。
以下是一个Python代码示例,用于模拟Flocking模型
import numpy as np
class Agent:
def __init__(self, x, y, vx, vy):
self.position = np.array([x, y])
self.velocity = np.array([vx, vy])
class Flock:
def __init__(self, agents):
self.agents = agents
def separation(self, agent, max_distance=1.0):
s = np.array([0.0, 0.0])
for other in self.agents:
if other == agent:
continue
distance = np.linalg.norm(agent.position - other.position)
if distance < max_distance:
s -= (other.position - agent.position)
return s
def alignment(self, agent):
average_velocity = np.array([0.0, 0.0])
for other in self.agents:
if other == agent:
continue
average_velocity += other.velocity
return average_velocity / (len(self.agents) - 1)
def cohesion(self, agent):
average_position = np.array([0.0, 0.0])
for other in self.agents:
if other == agent:
continue
average_position += other.position
return (average_position / (len(self.agents) - 1)) - agent.position
def update(self, w1=1.0, w2=1.0, w3=1.0, max_speed=1.0, dt=0.01):
for agent in self.agents:
v1 = self.separation(agent)
v2 = self.alignment(agent)
v3 = self.cohesion(agent)
agent.velocity += w1*v1 + w2*v2 + w3*v3
speed = np.linalg.norm(agent.velocity)
if speed > max_speed:
agent.velocity = (agent.velocity / speed) * max_speed
agent.position += agent.velocity * dt
这个代码定义了Agent
和Flock
两个类。每个Agent
有位置和速度属性。Flock
包含了一个代理列表,并有用于计算分离、对齐和凝聚向量的方法。update
方法用于更新群体中每个智能体的速度和位置。
使用这个代码,你可以创建一些智能体,然后将它们放入一个Flock
对象中,并多次调用update
方法来模拟群体行为:
agents = [Agent(np.random.rand()*10, np.random.rand()*10, 0, 0) for _ in range(10)]
flock = Flock(agents)
for _ in range(1000):
flock.update()