Beispiel #1
0
def test_relabel_selfloop():
    G = nx.DiGraph([(1, 1), (1, 2), (2, 3)])
    G = nx.relabel_nodes(G, {1: 'One', 2: 'Two', 3: 'Three'}, copy=False)
    assert sorted(G.nodes()) == ['One', 'Three', 'Two']
    G = nx.MultiDiGraph([(1, 1), (1, 2), (2, 3)])
    G = nx.relabel_nodes(G, {1: 'One', 2: 'Two', 3: 'Three'}, copy=False)
    assert sorted(G.nodes()) == ['One', 'Three', 'Two']
    G = nx.MultiDiGraph([(1, 1)])
    G = nx.relabel_nodes(G, {1: 0}, copy=False)
    assert sorted(G.nodes()) == [0]
Beispiel #2
0
def load_graphdata():

    loaded_trips = load_trips()
    print('{} trips loaded'.format(len(loaded_trips)))

    g = nx.MultiDiGraph()
    for i, trip in enumerate(loaded_trips):
        source, geopoints = trip

        for first, second in list(pairwise(iter(geopoints))):
            g.add_edge(first, second, key=i, source=source)

        #add start & endpoints
        g.nodes[geopoints[0]].setdefault('start', []).append(i)
        g.nodes[geopoints[-1]].setdefault('end', []).append(i)

        #add current trip to nodes
        for point in geopoints:
            g.nodes[point].setdefault('trips', []).append(i)

    startpoints = [n for n in g.nodes(data='start') if n[1] is not None]
    print('start: {}'.format(startpoints))

    endpoints = [n for n in g.nodes(data='end') if n[1] is not None]
    print('end: {}'.format(endpoints))

    print('{} nodes {} edges'.format(g.number_of_nodes(), g.number_of_edges()))

    return g
Beispiel #3
0
    def __init__(self):
        """Initialize the network topology"""

        # Topology as MultiDiGraph (MultiDi - Since each link is two unidirectional edges)
        self._topo = nx.MultiDiGraph()
        self._net_pids = {}  # Pin_Name -> Pid object
        self._topo_version = 0  # Each topology change should change the version number

        self.core_data = CoreNetData()
        self.core_data.load_data(r'/tmp/netdata.json')
Beispiel #4
0
    def create_graph(self):
        """Composes the graphs of the different plugins into a single graph.
        """

        # create conversion graph based on loaded plugins
        plugin_graphs = []
        for plugin in self.plugins:
            plugin_graphs.append(plugin.obj.get_supported_conversions_graph())

        joined_graph = nx.MultiDiGraph()
        for graph in plugin_graphs:
            joined_graph.add_edges_from(graph.edges(data=True))
        return joined_graph
Beispiel #5
0
    def _generate_graph(self):
        """Generate a directed graph where each node is a document format.
        The representation of a node pointing to another (e.g. from '.doc' to
        '.odt') is called edge and it will contain the name of the plugin being
        able to perform the conversion.
        The graph is the representation of all the format conversions provided
        by this plugin.
        """
        G = nx.MultiDiGraph()
        conversions = self.get_supported_conversions()
        self._add_priority_to_conversions(self._get_plugin_priority(),
                                          conversions)

        G.add_edges_from(conversions, plugin=self._get_module_name())
        return G
Beispiel #6
0
def demo_pytorch_computational_graph(
    t,
    init_gradient=None,
    figsize=(12, 6),
    padding=40
):
    import torch
    import networkx as nx
    import numpy as np
    import matplotlib.pyplot as plt

    if init_gradient is None:
        init_gradient = torch.tensor(1.0)

    G_forward = nx.DiGraph()  # for layout
    G = nx.MultiDiGraph()
    stack = [(t.grad_fn, t.grad_fn(init_gradient))]
    node_labels = {}
    while stack:
        node, outer_gradient = stack.pop()
        node_id = str(id(node)) + node.name()
        node_labels[node_id] = node.name()
        for n, n_outer_gradient in zip(node.next_functions, outer_gradient):
            if n[0] is not None:
                n_id = str(id(n[0])) + n[0].name()
                node_labels[n_id] = n[0].name()
                G_forward.add_edge(n_id, node_id)
                G.add_edge(node_id, n_id, label=n_outer_gradient.item())
                stack.append((n[0], n[0](n_outer_gradient)))
    # place nodes left-to-right
    # "regular" top-to-bottom layout
    nodes_layout = nx.nx_pydot.graphviz_layout(G_forward, prog='dot')
    # make right-to-left from top-to-bottom
    nodes_layout = {k: (-v[1], v[0]) for k, v in nodes_layout.items()}

    # visualize
    x_min = min([c[0] for c in nodes_layout.values()])
    x_max = max([c[0] for c in nodes_layout.values()])
    y_min = min([c[1] for c in nodes_layout.values()])
    y_max = max([c[1] for c in nodes_layout.values()])

    plt.figure(figsize=figsize)
    plt.xlim(x_min - padding, x_max + padding)
    plt.ylim(y_min - padding, y_max + padding)
    # draw nodes
    nx.draw_networkx_nodes(G, node_color="#a2c4fc", pos=nodes_layout)
    nx.draw_networkx_labels(G, pos=nodes_layout, labels=node_labels)
    # draw edges
    for e in G.edges:
        l = G.edges[e]["label"]
        current_multiplicity = e[2]
        coords = tuple(0.5 * (np.array(nodes_layout[e[0]]) + np.array(nodes_layout[e[1]])) - 10 * current_multiplicity)
        plt.annotate(l, coords, color="r", ha='center')
        # hacky arrows
        plt.annotate(
            "",
            xy=nodes_layout[e[1]], xycoords='data',
            xytext=nodes_layout[e[0]], textcoords='data',
            arrowprops=dict(
                arrowstyle="simple",
                color="r",
                alpha=0.5,
                shrinkA=10, shrinkB=10,
                connectionstyle="arc3,rad={}".format(-0.1*(1 + current_multiplicity))
            ),
        )
Beispiel #7
0
### Task 1 ###
from networkx import nx
import random
from collections import defaultdict

## generate (directed) GNP random graph
G = nx.MultiDiGraph(nx.gnp_random_graph(200, 0.4, directed=True))
visit_freq_map = defaultdict(int)  # to count node visits

for i in range(100):
    H = G.copy()
    currNode = 0
    while (random.random() >= 0.2):
        new_link = list(H.edges(currNode))[random.randint(
            0,
            len(H.edges(currNode)) - 1)]
        H.add_edge(new_link[0], new_link[1])  # to increase visit probability
        currNode = new_link[1]
        visit_freq_map[currNode] += 1

# print out nodes by frequency of visit in descending order
print("nodes by frequency of visit:")
print(sorted(visit_freq_map.items(), key=lambda kv: kv[1], reverse=True))

### Task 2 ###

from surprise import Dataset
from surprise.model_selection import cross_validate
from surprise import SVD
from surprise import NMF