Esempio n. 1
0
def iter_random_walk(
    G: nx.Graph, n: Hashable, weight: Optional[str] = None
) -> Iterable[Hashable]:
    """
    Given an input graph and a root node, repeatedly yield the results of a random walk starting with the root
    node; if the node is disconnected then the walk will consist just of the node itself.

    :param G: input graph
    :param n: root node
    :param weight: name of weight attribute to use, or None to disable, default None
    :return: yields nodes in a random walk, starting with the root node
    """

    def _next_node(node):
        if len(G[node]) == 1:
            return list(G[node])[0]  # if there is one node, return it
        elif weight is None:
            return random.choice(
                list(G[node])
            )  # if there is are weights, simply pick the next node at random
        else:
            nodes = []
            weights = []
            for _, to_node, to_weight in G.edges(node, data=weight, default=0):
                nodes.append(to_node)
                weights.append(to_weight)
            weights = np.array(weights)
            return nodes[
                np.random.choice(np.arange(len(nodes)), p=weights / weights.sum())
            ]

    if len(G[n]) == 0:
        return  # if there are no adjacent nodes to the start node, do not iterate
    yield from iterate(_next_node, n)
Esempio n. 2
0
def squareroot(N, eps):
    def _improve(a):
        return (a + N/a) / 2.0

    def _within(gen):
        prev = gen.next()
        cur = gen.next()
        while abs(cur - prev) > eps:
            prev = cur
            cur = gen.next()
        return cur

    return _within(iterate(_improve, 1))
Esempio n. 3
0
def squareroot(N, eps):
    def _improve(a):
        return (a + N / a) / 2.0

    def _within(gen):
        prev = gen.next()
        cur = gen.next()
        while abs(cur - prev) > eps:
            prev = cur
            cur = gen.next()
        return cur

    return _within(iterate(_improve, 1))
Esempio n. 4
0
def test_iterate():
    assert list(itertools.islice(iterate(inc, 0), 0, 5)) == [0, 1, 2, 3, 4]
    assert list(take(4, iterate(double, 1))) == [1, 2, 4, 8]
Esempio n. 5
0
def test_iterate():
    assert list(itertools.islice(iterate(inc, 0), 0, 5)) == [0, 1, 2, 3, 4]
    assert list(take(4, iterate(double, 1))) == [1, 2, 4, 8]