Как создать график пользователей в python, чтобы существовала грань между двумя пользователями, если расстояние между этими двумя пользователями меньше некоторого значения? - PullRequest
1 голос
/ 26 апреля 2020

Я хочу иметь неориентированный график

image

so that V is the set of all users (represented by their 3D locations) and E is the set of links between the users, with the condition that the link exists only if the distance between the two nodes is within some threshold. I found a library called networkx , но не нашел, как добавить ребра на основе условия расстояния.

1 Ответ

0 голосов
/ 26 апреля 2020

Я смог сделать это, инициализировав график из массива numpy, чтобы расстояние между узлами стало весом, а затем выполнив все значения oop над весами, чтобы удалить ребро, если расстояние превышает некоторый порог R .

import networkx as nx
import random
from scipy.spatial.distance import pdist, squareform

random.seed(42)

# user locations
def initialize_area():
    x_vals = random.sample(range(1, L-1), I) # I is number of users, L length and B breadth
    y_vals = random.sample(range(1, B-1), I)
    z_vals = [0]*I

    coordinates = list(zip(x_vals,y_vals,z_vals))
    # plt.scatter(*zip(*coordinates))
    plt.scatter(x_vals, y_vals)
    # print(coordinates)
    plt.xlabel("X-axis (m)")
    plt.ylabel("Y-axis (m)")
    plt.title('Simulation Area')
    plt.show()
    print("coordinates = ", coordinates)
    create_graph(coordinates)

def create_graph(coordinates):
    A = np.array(coordinates)
    B = squareform(pdist(A))
    print("B=", B)
    G = nx.from_numpy_matrix(B)
    for i in range(I):
        for j in range(I):
            if G.get_edge_data(i,j) !=None:
                if (G.get_edge_data(i,j)['weight']>R):
                    # print("i=",i, "j=",j)
                    G.remove_edge(i,j)
    analyze_graph(G)


def analyze_graph(G):
    nx.draw(G)
    print("nodes=", G.number_of_nodes(), "edges=", G.number_of_edges())
    plt.show()
    # for i in range(I):
    #     for j in range(I):
    #         print( "i=",i,"j=",j,G.get_edge_data(i,j))



if __name__ == '__main__':
    initialize_area()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...