Hello there awesome community!
I am writing a discrete 2d multi-agent environment in Python. I want my agents to share information when they are in the vicinity of each other. What is the best way to go about detecting agents in vicinity to one another?
My initial thought is to get the distances between all agents using some get_distances()
method which takes in a vector of agents positions and spits out a distance matrix (any kind of distance, but L1 preferrably), something like this:
>> positions = np.array([[agent_0_row, agent_0_col],
[agent_1_row, agent_1_col],
[agent_2_row, agent_2_col]])
>> get_distances(positions)
np.array([[d_00, d_01, d_02],
[d_10, d_11, d_12],
[d_20, d_21, d_22]])
where d_ab
is the distance between agent a and agent b. And then check for distances that are below a certain threshold. Is there a Numpy built-in function like the get_distances()
one? or is there even a better way of going about this?
CodePudding user response:
You can do this with numpy broadcasting, you just need to add different new axes to two slices of your positions
array:
def get_distances(positions):
relative_positions = positions[None, :, :] - positions[:, None, :]
# now do the distance calculation however you want, here's L1:
distances = np.abs(relative_positions).sum(axis=2)
return distances