Beispiel #1
0
def plot_graph(args):
    if not isinstance(args.dataset, list):
        args.dataset = [args.dataset]

    for name in args.dataset:
        dataset = build_dataset_from_name(name)
        data = dataset[0]

        depth = args.depth
        pic_file = osp.join(args.save_dir, f'display_{name}.png')

        col_names = [
            'Dataset', '#nodes', '#edges', '#features', '#classes',
            '#labeled data'
        ]
        tab_data = [[
            name, data.x.shape[0], data.edge_index.shape[1], data.x.shape[1],
            len(set(data.y.numpy())),
            sum(data.train_mask.numpy())
        ]]
        print(tabulate(tab_data, headers=col_names, tablefmt='psql'))

        G = nx.Graph()
        G.add_edges_from([
            tuple(data.edge_index[:, i].numpy())
            for i in range(data.edge_index.shape[1])
        ])

        s = random.choice(list(G.nodes()))
        q = [s]
        node_set = set([s])
        node_index = {s: 0}
        max_index = 1
        for _ in range(depth):
            nq = []
            for x in q:
                for key in G[x].keys():
                    if key not in node_set:
                        nq.append(key)
                        node_set.add(key)
                        node_index[key] = node_index[x] + 1
            if len(nq) > 0:
                max_index += 1
            q = nq

        cmap = cm.rainbow(np.linspace(0.0, 1.0, max_index))

        for node, index in node_index.items():
            G.nodes[node]['color'] = cmap[index]
            G.nodes[node]['size'] = (max_index - index) * 50

        fig, ax = plt.subplots()
        plot_network(G.subgraph(list(node_set)), node_style=use_attributes())
        plt.savefig(pic_file)
        print(f'Sampled ego network saved to {pic_file} .')
Beispiel #2
0
    def _call(self, dataset="cora", seed=-1, depth=3, **kwargs):
        if isinstance(dataset, list):
            dataset = dataset[0]
        name = dataset
        dataset = build_dataset_from_name(name)
        data = dataset[0]

        G = nx.Graph()
        edge_index = torch.stack(data.edge_index)
        G.add_edges_from([
            tuple(edge_index[:, i].numpy()) for i in range(edge_index.shape[1])
        ])

        if seed == -1:
            seed = random.choice(list(G.nodes()))
        q = [seed]
        node_set = set([seed])
        node_index = {seed: 0}
        max_index = 1
        for _ in range(depth):
            nq = []
            for x in q:
                for key in G[x].keys():
                    if key not in node_set:
                        nq.append(key)
                        node_set.add(key)
                        node_index[key] = node_index[x] + 1
            if len(nq) > 0:
                max_index += 1
            q = nq

        cmap = cm.rainbow(np.linspace(0.0, 1.0, max_index))

        for node, index in node_index.items():
            G.nodes[node]["color"] = cmap[index]
            G.nodes[node]["size"] = (max_index - index) * 50

        pic_file = f"{name}.png"
        plt.subplots()
        plot_network(G.subgraph(list(node_set)), node_style=use_attributes())
        plt.savefig(pic_file)
        print(f"Sampled ego network saved to {pic_file}")

        return q
import matplotlib.pyplot as plt

from grave import plot_network, use_attributes

toy_network = nx.barbell_graph(10, 14)
toy_centrality = closeness_centrality(toy_network)
max_centrality = max(toy_centrality.values())

for u, v, edge_attributes in toy_network.edges.data():
    c = (toy_centrality[u] + toy_centrality[v]) / 2
    color_idx = (c / max_centrality)
    cmap = plt.get_cmap()
    edge_attributes['color'] = cmap(color_idx)
    edge_attributes['width'] = 2

for node, node_attributes in toy_network.nodes.data():
    node_attributes['size'] = (1 - (toy_centrality[node] / max_centrality) +
                               .1) * 100


def edge_style(edge_attributes):
    return {'linewidth': edge_attributes.get('weight', 1)}


fig, ax = plt.subplots()
plot_network(toy_network,
             layout='spring',
             node_style=use_attributes(),
             edge_style=use_attributes('color'))
plt.show()
Beispiel #4
0
"""
Grave Documentation
-------------------

"""
import networkx as nx
from networkx.algorithms.approximation.dominating_set import min_weighted_dominating_set
import matplotlib.pyplot as plt

from grave import plot_network, use_attributes

toy_network = nx.barbell_graph(10, 14)
dom_set = min_weighted_dominating_set(toy_network)

for node, node_attrs in toy_network.nodes(data=True):
    if node in dom_set:
        node_attrs['color'] = 'red'
    else:
        node_attrs['color'] = 'black'
    node_attrs['size'] = 50

fig, ax = plt.subplots()
plot_network(toy_network, node_style=use_attributes())
plt.show()
Beispiel #5
0
    # create attribute for label
    nx.set_edge_attributes(H,
                           {e: G.edges[e]['weight'] for e in H.edges},
                           'label')

    # create stylers
    def transfer_G_layout(network):
        return {n: G.position[n] for n in network}

    def elabel_base_style(attr):
        return {'font_size': 4,
                'font_weight': 'bold',
                'font_family': 'sans-serif',
                'font_color': 'b',
                'rotate': True,  # TODO: make rotation less granular
                }

    elabel_style = grave.style_merger(grave.use_attributes('label'),
                                      elabel_base_style)

    grave.plot_network(H, transfer_G_layout,
                       node_style=dict(node_size=20),
                       edge_label_style=elabel_style,
                       node_label_style={'font_weight': 'bold'})

    # scale the axes equally
    plt.xlim(-5000, 500)
    plt.ylim(-2000, 3500)

    plt.show()