コード例 #1
0
def init_graph(n: int, d: int, seed=None) -> nx.Graph:
    """
    Initialize graph with n nodes, and d degree for Albert-Barabasi.
    :param n:
    :param d:
    :return:
    """
    import types

    # init barabasi-albert graph
    g: nx.Graph = nx.generators.random_graphs.barabasi_albert_graph(n, d, seed)

    # add node data to each node
    for _, data in g.nodes(data=True):
        data['data'] = NodeInfo.init_random()

    # add edge data to each edge
    for a, b, data in g.edges(data=True):
        _init_edge(g, a, b)

    # add custom add_edge method to graph
    # g.add_edge_with_init = types.MethodType(_add_edge, g)
    # g.update_fee = types.MethodType(_update_fee, g)
    # g.get_policy = types.MethodType(_get_policy, g)

    nx.Graph.add_edge_with_init = _add_edge
    nx.Graph.update_fee = _update_fee
    nx.Graph.get_policy = _get_policy

    return g
コード例 #2
0
def setup_graph(m=0, n=0):
    """ Sets up graph with last node as adversary with two existing channels.
    Caches graph for repeated use.
    """
    if not setup_graph.first_call:
        return nx.read_gpickle('graphstore.temp')
    else:
        setup_graph.first_call = False

        graph = init_graph(m, n)
        new_node = len(graph)
        graph.add_node(new_node, data=NodeInfo.init_random())

        # make initial channels for new node
        highest_degrees = sorted(
            graph.nodes, key=lambda node: len(graph[node]), reverse=True)
        e1, e2 = highest_degrees[0:2]
        graph.add_edge_with_init(new_node, e1, default=True)
        graph.add_edge_with_init(new_node, e2, default=True)

        # save graph for different runs
        nx.write_gpickle(graph, 'graphstore.temp')

        # debugging
        log.write('''## Graph used
|node |neighbours|
| --- | --- |
''')
        log.write('\n'.join(f'|{node:>4d} |{list(neighbours.keys())} |'
                            for node, neighbours in graph.adjacency()) + '\n --- \n')

        return graph