How to deals with unknown label and edges in python graph

左心房为你撑大大i 提交于 2020-12-15 19:37:50

问题


I have two arrays, a and b. I would like to draw the networkx graph that group the values together which are close to each other and label them accordingly. Any idea how to do this?


回答1:


Finding close pairs

Your algorithm finds closest point of b to each point of a but you need to identify a list of them within some threshold for distance (which might be empty in most of cases). This can be achieved with an assist of scipy.spatial.KDTree:

import numpy as np
from scipy.spatial import KDTree
from itertools import chain
def nearby_pts(a, b, distance):
    # indices of close points of `b` for each point of `a`
    a_data, b_data = np.expand_dims(a, axis=1), np.expand_dims(b, axis=1)
    idx = KDTree(b_data).query_ball_point(a_data, r=distance)
    return idx

Then you can find edges that joins pairs of indices of close points from a to b. This can't be vectorized fully but I made the best I can out of it:

def close_pairs(a, b, distance):
    pts = nearby_pts(a, b, distance).tolist()
    pts_flatten = list(chain(*pts))
    idx = np.repeat(np.arange(len(pts)), [len(n) for n in pts])
    return np.c_[idx, pts_flatten]

Output:

>>> close_pairs(a, b, distance=150)
[[0, 12], [1, 11], [2, 13], [3, 7], [5, 10], [5, 15], [6, 8], [7, 1], [8, 2], [9, 3], [9, 14], [10, 0], [11, 6], [12, 4], [13, 5], [13, 15], [14, 3], [15, 10]]

Plotting a graph

Now you're ready to create a graph from edges found but first you need to relabel a second section of nodes (b) not to be duplicated with a section. So you can just add len(a) to indices of nodes of b and that's it:

import igraph as ig

pairs_relabel = close_pairs(a, b, distance=150) + [0, len(a)]
g = ig.Graph(n = len(a) + len(b))
g.add_edges(pairs_relabel)

pal = ig.drawing.colors.ClusterColoringPalette(2) #number of colors used is 2
color = pal.get_many([0]*len(a)+[1]*len(b)) #tags of colors
labels = np.r_[a.astype(int), b.astype(int)] #labels are integral values of nodes

ig.plot(g, bbox=(500, 300), vertex_size=24, 
        vertex_color = color, vertex_label_size=9, vertex_label = labels)



来源:https://stackoverflow.com/questions/64292966/how-to-deals-with-unknown-label-and-edges-in-python-graph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!