Skip to content

FEAT: Added basic random walk utilities #8378 - #8383

Merged
dschult merged 11 commits into
networkx:mainfrom
NeelMishra:feature-request-randomwalk-algorithms
Feb 17, 2026
Merged

dschult merged 11 commits into
networkx:mainfrom
NeelMishra:feature-request-randomwalk-algorithms

Conversation

@NeelMishra

@NeelMishra NeelMishra commented Dec 13, 2025 •

Copy link
Copy Markdown
Contributor

This PR is in reference with the following idea discussion : #8378

-> added unweighted_random_walk and weighted_random_walk to networkx.algorithms.walks, including input validation, seeded RNG support, and clear behavior for zero/negative weights

Thanks @dschult for the support. Please let me know if I should revise something.

@NeelMishra
NeelMishra marked this pull request as draft December 13, 2025 15:53
@NeelMishra
NeelMishra marked this pull request as ready for review December 13, 2025 15:53

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Congrats on your first PR to NetworkX!

Could this be one function with the keyword arg "weight" used to determine whether it is a weighted or unweighted walk? That is, what is the difference between the unweighted walk function and the weighted walk with weighted=None?

I think the doc_string troubles are handled by the following:

  • use single backticks around argument names of the function, e.g. start. Double backticks are for code without any reference available (most things are double backticks).
  • To reference the Randomness doc-page use e.g.
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
  • G with single-ticks is a good way to refer to that variable.

I haven't looked slocely at the code yet. But there are first impressions. Thanks!

Comment thread networkx/algorithms/walks.py Resolved
Comment thread networkx/algorithms/walks.py Resolved
Comment thread networkx/algorithms/walks.py Resolved
@NeelMishra

Copy link
Copy Markdown
Contributor Author

Thanks @dschult , I really appreciate you taking the time to review this.

I have made the below changes to the previous code,

  • added a single random_walk function that supports both uniform and weight biased sampling via the existing weight= keyword
  • improved the code's documentation and rectified some of the earlier linter issue highlighted earlier
  • updated the walks reference page so random_walk appears alongside number_of_walks
  • changed the previous tests to facilitate the combined random walk function, primarily covering : determinism, dead ends, zero/negative weight cases, and negative weight attrs when running unweighted random walk.

All the tests are passing right now. Please let me know if anything needs to be modified.

I also noticed a failing check that says the PR needs a type: label. I am not sure how to resolve that from my side...

@amcandio amcandio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Implementation LGTM. I have a couple questions on the API

Comment thread networkx/algorithms/walks.py Outdated

@nx._dispatchable
@py_random_state("seed")
def random_walk(G, start, walk_length, *, weight=None, seed=None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should start be optional? Maybe we want to make the length optional too and have a stop probability?

I'm not an expert here but it would be great to check how other algorithms use random walks. That would help pick the right API

@NeelMishra NeelMishra Dec 14, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @amcandio, thanks for the review. I found an existing helper generate_random_paths in networkx.algorithms.similarity. It can take an optional start node, but it’s quite different in scope and approach.

To state a few major differences:

• generate_random_paths is a batch generator (sample_size paths) and can build an index_map for the similarity workflow, while this PR is a small single walk primitive intended to live in algorithms.walks.

• Even with source set, generate_random_paths builds an n x n adjacency and transition probabilities up front, whereas this function samples step by step from the current node’s neighbors. The matrix setup can be a lot for large sparse graphs.

My preference is to keep start required. Making it optional raises a few “what does uniform mean here” questions (isolates, directed graphs with sinks, etc), and also needs which distribution to use in order to choose the start node.

Also it is easy for callers to sample a start node explicitly when they want that behavior. It is just a slight preference on my end, and I am completely onboard with what the team decides.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm generally aligned with @amcandio here in terms of taking time to work carefully through the API.

Re: start, my initial feeling (without having thought about this too hard) would be to instead have a keyword argument named nodes which can be either None, a sequences of nodes, or a single node. If None, then run the random walk for all nodes, producing a dict keyed by node to the walk. If nodes is a subset, then perform the walk only for that subset; and finally if it's a single node perform the walk for that node.

The reason I bring this up is that I think it's consistent with patterns used elsewhere in NetworkX.

Re: generate_random_paths - IMO this function shouldn't be considered in the design of random_walks (though it was a good find @NeelMishra !) IMO the generate_random_paths function has some quirky implementation details (most notably the modify-dicts-across-scope-boundaries) that are hard to reason about in user code. I think ultimately I'd propose to "deprecate" generate_random_paths (i.e. make it private) in favor of this function. All that's to say - let's not try to match the generate_random_paths patterns here and instead start with a clean slate!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I'm +1 on an optional argument that it's either None, a node or a collection

@dschult dschult Dec 18, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When would you want to generate a random walk from each of the nodes? Or even from a subset of the nodes? Maybe I don't understand the use-case, but at first glance I'd think you'd want many walks from the same starting node, not one walk from many specified starting nodes.

Either that or we treat the function as always generating one walk from a specified starting node -- which is what this PR currently does. I guess the downside is an extra function call for each walk generated.

How are we expecting people to use this function? I doubt they will want to only generate one walk for one starting node. So, is it better to build the API to have user specify the number of walks and each starting node? Or is it better to provide a function for a single walk with specified starting node and make the user build the larger structure through repeated calls.

My suspision is that having the user make multiple calls is the cleaner interface -- so long as the performance isn't much worse. But I think it depends what this will be used for. Let's say it is something like node2vec. How would this get used for that?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IT looks like cugraph's random walk generator tools have the user provide an array of starting nodes. They they are related to the node2vec machinery there.

So... let's make the start node an optional from None, iterable of nodes, single node. It can be processed using G.nbunch_iter(start) if that is easy. Then a loop around the walk code. Does this sound good?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requiring start keeps the behavior completely explicit. The caller decides where the walk begins, and we avoid having to define extra policy in the API such as how to choose start nodes when none is provided, whether isolates or directed sinks are skipped, and what uniform should mean when some nodes cannot take a step.

At the same time, many users will want bulk generation. Node2vec and DeepWalk are good examples of that, and those are closer to many walks from many start nodes (often all nodes) than a single walk in isolation. networkx already has generate_random_paths for bulk sampling, which seems like a reasonable fit for those workflows.

The main difference is the cost model. generate_random_paths builds a dense n×n transition matrix up front. That is convenient, but it has O(n^2) time and memory overhead even when the graph is large and sparse, and even if the user only wants a limited number of walks (or walks from only a few start nodes).

A step by step walk that samples neighbors directly from the adjacency is closer to O(num_walks × walk_length), which can be a better default for sparse graphs and for local tasks.

Workflows that benefit directly from the current utility include monte carlo personalized pagerank / random walk with restart from a query or seed node, local exploration and sampling from a seed set, and downstream embedding or sampling pipelines where the caller already controls how many walks to run from a given start node.

If we keep the function as the explicit single walk primitive, I can rename it to make that intent clearer. random_walk_from_node, random_walk_from_source etc could be good alternatives..

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @dschult , please help us with a direction on this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

networkx already has generate_random_paths for bulk sampling

There are many warts associated with that function - my goal would be to replace it with this one.

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Hi @dschult and @amcandio. Just a gentle nudge on this PR 😅 . Happy to make further changes if needed. Thanks.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It sounds like we need a motivation for this function. We already have something for random paths. These are random walks. Is that the motivation for a new function? I seem to recall that the random paths function actually returns walks. But I haven't check that.

Is the motivation to refactor the method in random paths to avoid the implicit all-to-all storage of using a full matrix?

As for the one-source versus many sources discussion, why would we only want one source? That requires calling this function many times -- which can be expensive. It is only very slightly more work to have a loop over one source than to just process one source and return. And it removes what might be a common idiom of calling this function inside a loop over sources.

Might we want to allow the sources input to allow repeated nodes so we get multiple walks for the same source? What is the disadvantages of having the function return walks from multiple sources or many walks from the same sources?

Comment thread networkx/algorithms/walks.py Outdated

# Fast path: unweighted / uniform
if weight is None:
current = neighbors[seed.randrange(len(neighbors))]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC we probably want current = seed.choice(neighbors)

Comment thread networkx/algorithms/walks.py Outdated
Comment on lines +122 to +123
if not neighbors:
break

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like the only way we break is for the start node to have no neighbors.
If current is not start, then we got to start somehow and we can retrace back out of that node.
At least for undirected graphs we don't ever hit a deadend. I see now that we could reach this condition if we have a directed graph.

Are we trying to make this work for directed/undirected and whether multigraph or not?

Comment thread networkx/algorithms/walks.py Outdated
Comment on lines +156 to +157
if not weight_map:
break

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the only way to get to this break is if neighbors is an empty list or if an edge weight is 0.

How do we want to treat edges with weight zero? (Can we just raise a valueerror like for negative weights?

Comment thread networkx/algorithms/walks.py Outdated

@nx._dispatchable
@py_random_state("seed")
def random_walk(G, start, walk_length, *, weight=None, seed=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IT looks like cugraph's random walk generator tools have the user provide an array of starting nodes. They they are related to the node2vec machinery there.

So... let's make the start node an optional from None, iterable of nodes, single node. It can be processed using G.nbunch_iter(start) if that is easy. Then a loop around the walk code. Does this sound good?

@rossbar

rossbar commented Jan 23, 2026

Copy link
Copy Markdown
Contributor

Okay I've spent an afternoon thinking about this and arrived at a set of questions that I think it's important to answer:

  • walk_length (or similar) seems like a reasonable parameter for the walk, but what happens when a walk terminates at less than the length. For example, what should the result of nx.random_walk(nx.path_graph(3, create_using=nx.DiGraph), source=0, walk_length=5) be? Obviously the walk isn't "random" in this case.
  • A more trivial case of the above is isolated nodes. What should the result of nx.random_walk(nx.empty_graph(1), 0, walk_length=10) be?
  • @amcandio raises a good point about whether walk_length should even be required, though I think there would be ways to create random walks with probabilistic termination conditions using a custom weight function.
  • Handling multiedges by summing weights across all edges makes sense (I think), though raising on any negative weight in that case feels too restrictive - I'd think as long as the sum of all the parallel edge weights is positive then that'd be okay. Of course, we could always punt on the multi-graph issue for now, forcing users to condense multi-edge weights themselves.

I don't have consistent mental model to be able to confidently answer these questions, though my expectations for behavior might look something like this:

# Isolated nodes
>>> G = nx.empty_graph(0)
>>> nx.random_walk(G, nodes=0, walk_length=10)  # No edges == walk is "empty"
[]
# Terminal nodes / deterministic walks (as dictated by connectivity)
>>> G = nx.DiGraph([(0, 1), (1, 2)])
>>> nx.random_walk(G, nodes=0, walk_length=10)  # Return the walk, even if it's shorter than walk_length
[0, 1, 2]
# Self-loops
>>> G = nx.Graph([(1, 1)])
>>> nx.random_walk(G, nodes=1, walk_length=5)  # Self-loop edges are valid
[1, 1, 1, 1, 1]
# `nodes` supports single node, a subset, or all nodes (obviously the walks themselves in the examples below are random)
>>> G = nx.cycle_graph(3)
>>> nx.random_walk(G, nodes=0, walk_length=3)
[0, 2, 0]
>>> nx.random_walk(G, nodes={0, 1}, walk_length=3)
{0: [0, 2, 1], 1: [1, 0, 2]}
>>> nx.random_walk(G, walk_length=3)  # default is nodes=None
{0: [0, 1, 0], 1: [1, 2, 1], 2: [2, 0, 1]}
# How one might generate 1000 random walks of length (at most) `n` from a node:
>>> my_walks_from_n = [nx.random_walk(G, node=0, walk_length=n) for _ in range(1000)]
# This could be done reproducibly by seeding outside the loop
>>> my_seed = np.default_rng(0xdeadc0de)
>>> my_reproducible_walks = [nx.random_walk(G, node=0, walk_length=n, seed=my_seed) for _ in range(1000)]

@dschult

dschult commented Jan 29, 2026

Copy link
Copy Markdown
Member

There is a not-very-maintained package graph-walker where the link describes the public facing functions (thanks to @rlratzel for the link). I think we are probably aiming for something more low level... like a function that returns one walk from one starting node. Then people could use that along with list or dict comprehensions to collect data for many walks from many starting values.

I'm in favor of most of the suggestions in the previous comment. In addition it seems popular to include an optional "restart" probability alpha . Anogther common feature seems to be to allow inputs of p and q from the node2vec world (instead of weights? in addition to weights?). It feels like that ought to be a different function though.

It seems like walk_length cannot always be the same (e.g. when there are dead-ends) but there must be a standard meaning to that term because it is used frequently and rarely explained in detail. :)

@NeelMishra

NeelMishra commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the discussion, Dan and Ross. I think it may help to clarify how I was thinking about the scope of this function.

My intent was for this to be a small, low-level primitive that generates random walks from explicitly specified start nodes, rather than implicitly operating over the entire graph. Supporting an optional start node or a small user defined set of start nodes fits this model well.

Within that scope, I considered walk_length as an upper bound rather than a guarantee. Early termination is therefore a valid, particularly for directed graphs, sinks, or isolated nodes.

Batching can be limiting, especially when walks need to be generated conditionally or sequentially, when per-walk control matters, or when memory usage should remain proportional to a single walk (sparse graphs). For this reason, I prefer to keep this function as a single walk primitive rather than having only the full batch behavior.

Restart probability/weights (or even a custom transition function?) is a great addition, but I think it might be better to keep the function minimal and consider those extensions as separate, more specialized functions.

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Thanks for the help, Dan and Ross. I’ve tried to incorporate the feedback while keeping the function small and explicit.

The implementation introduces a single walk primitive, random_walk_single_source, supporting both weighted and unweighted behavior via the weight= keyword. The goal is to make a “single walk from a chosen start node” intuitive, without bundling batching semantics into the core API.

The start argument is optional: if none, a random node is sampled from G; otherwise, a valid node is required and NodeNotFound is raised if missing. Early termination is preserved, so walk_length acts as an upper bound rather than a guarantee.

I also kept walk_length optional. When none, a length is sampled uniformly from [0, |V|] (inclusive), which supports a common random-length variant without introducing additional parameters.

I incorporated the suggestion to use seed.choice(neighbors).

Batching, restarts, p/q, and custom transition logic are intentionally out of scope here and feel better suited to higher-level utilities/functions.

Comment thread networkx/algorithms/walks.py Resolved
Comment thread networkx/algorithms/walks.py Outdated
@nx._dispatchable(edge_attrs="weight")
@py_random_state("seed")
def random_walk_single_source(
G, start=None, walk_length=None, *, weight=None, seed=None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO start and walk_length should not have defaults - let's force the user to specify them!

Comment thread networkx/algorithms/walks.py Outdated
def random_walk_single_source(
G, start=None, walk_length=None, *, weight=None, seed=None
):
"""Generate a random walk starting at `start`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"""Generate a random walk starting at `start`.
"""Returns a random walk starting at `start`.

Comment thread networkx/algorithms/walks.py Outdated
Comment on lines +143 to +162
# Weighted path
weight_map = {}
for neighbor in neighbors:
if is_multigraph:
total = 0
# Iterate over parallel edges between `current` and `neighbor`.
for data in G[current][neighbor].values():
val = data.get(weight, 1)
if val < 0:
raise ValueError(
f"Edge ({current}, {neighbor}) has negative weight {val}"
)
total += val
else:
data = G[current][neighbor]
val = data.get(weight, 1)
if val < 0:
raise ValueError(
f"Edge ({current}, {neighbor}) has negative weight {val}"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The handling of weighted edges adds a lot of code - it feels like this should be handled upstream... For example, random.choices supports weighted sampling - delegating to the built-in functionality would be much cleaner IMO.

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ended up being a really long post - here's the tl;dr...

I propose to go with the following implementation:

@nx.utils.not_implemented_for("multigraph")
@py_random_state("seed")
def random_walk(G, node, walk_length, *, weight=None, seed=None):
    """docstring"""
    walk = [node]
    for _ in range(walk_length):
        # If current node has no neighbors, terminate the walk
        if not (nbrs := G._adj[node]):
            return walk
        # Extract weights
        wts = [v.get(weight, 1) for v in nbrs.values()]
        # random.choices assumes weights are non-negative
        if any(wt < 0 for wt in wts):
            raise ValueError("weights cannot be negative")
        node = seed.choices(list(nbrs), weights=wts, k=1)[0]
        walk.append(node)
    return walk

with the following explicit decisions:

  1. No optimizations in this PR (i.e. no fast-paths for unweighted case, no caching of nbrs/wts)
  2. Exclude multigraph support

See below for a full dump of my thought process and the reasoning re: optimization and multigraph support!


I spent some more time thinking about this yesterday and was able to (I think) decompose the problem into bits of code that would need to be added to support various different things.

Fundamentally, random walks with a nested-dict data structure can be extremely simple. If we stick with simple (i.e. non-directed, non-multi) graphs, ignore isolated nodes, and limit ourselves to unweighted walks, it essentially boils down to:

def random_walk(G, node, walk_length):
    return [node] + [(node := seed.choice(G._adj[node])) for _ in range(walk_length)]

Now, as mentioned, this doesn't handle cases where there are no edges leaving a node, which can happen in two different contexts:

  1. The user passes in an isolated (i.e. degree 0) node as the start of the walk, and/or
  2. The graph is directed and the walk lands on a node with 0 out-degree.

The only thing we need to do to handle these cases is check for empty neighbors. Expanding on the previous example, we get something like:

def random_walk(G, node, walk_length):
    walk = [node]
    for _ in range(walk_length):
        # Here's the condition to handle the "no out edges" nodes
        if not (nbrs := G._adj[node]):
            return walk
        node = seed.choice(list(nbrs))
        walk.append(node)
    return walk

Okay - not too bad. Now what if we add support for weighted walks? As mentioned in my previous comment, random.choices already supports weighted random sampling, so the only thing we really need to add ourselves is the extraction of the weights from the adjacency data structure:

def random_walk(G, node, walk_length, weight):
    walk = [node]
    for _ in range(walk_length):
        # Our degree-0 check, same as before
        if not (nbrs := G._adj[node]):
            return walk
        # Now add weight extraction (note that we're implicitly relying
        # on insertion ordering to ensure the wts correspond to the correct
        # nbrs!
        wts = [v.get(weight, 1) for v in nbrs.values()]
        node = seed.choices(list(nbrs), weights=wts, k=1)[0]
        walk.append(node)
    return walk

Now, the extra dict lookups for the weights and the weighted sampling is obviously more computationally expensive than the unweighted scenario. So a question that arises is: does that justify a "fast path" for the weight=None case? This is inherently subjective. My proposal would be to not include any optimizations (i.e. special code branches for the unweighted case) to begin with. The advantage of a one-size-fits-all implementation is that we can then add benchmarks and use it as a baseline "slow" case. That would allow folks to make a more informed decision about whether optimizations1 are worth additional code complexity.

Finally - what about multigraphs? Well in principle it's as simple as replacing the wts extraction with an extra loop over keys, e.g.

wts = [sum(v.get("weight", 1) for v in keydict.values()) for keydict in nbrs.values()]

This assumes that summing the edge weights (or treating the number of parallel edges as the weight in the unweighted case) is the "correct" thing to do. At face value this makes sense, but I'm no expert and don't know of any actual applications of random walks applied to multigraphs. In the interest of incremental adoption, I'd personally be inclined to simply add not_implemented_for("multigraph") to start. That way, if users do have applications involving random walks on multigraphs, those use-cases can inform the design!

In summary then, I'd propose to go with the implementation proposed at the top of this comment!

Footnotes

  1. another obvious optimization would be to cache the nbrs/weights after first lookup, to eliminate the overhead of creating lists from the dict structures at each lookup. ↩

@rossbar

rossbar commented Feb 6, 2026

Copy link
Copy Markdown
Contributor

Another thing I failed to consider/mention previously - it's worth considering whether this should be a generator instead of a function. That would certainly make sense for use-cases where folks are interested in "targeted" random walks - i.e. generate a random walk until I reach a specified node or set of nodes.

@dschult

dschult commented Feb 8, 2026

Copy link
Copy Markdown
Member

Another thing I failed to consider/mention previously - it's worth considering whether this should be a generator instead of a function. That would certainly make sense for use-cases where folks are interested in "targeted" random walks - i.e. generate a random walk until I reach a specified node or set of nodes.

So the generator would yield nodes in the walk -- and StopIteration would occur when there are no outgoing edges from the node. Interesting... The people can get a walk with given walk_length using:

walk = [node for i, node in enumerate(random_walk(G, start=3)) if i < walk_length]

And to do many starting nodes or many walks with the same starting node they put that idiom inside a loop of their creation.

And if they want walks that last until it reaches a terminal set of nodes:

walk = [node for i, node in random_walk(G, start=3) if node not in terminal_nodes]

This does look interesting/effective/flexible... Something like:

def random_walk(G, start, weight=None):
    node = start
    while (nbrs := G._adj[node]):
        wts = None if weight is None else [
            nbr.get(weight, 1) for nbr in nbrs.values()
            ]
        node = seed.choices(list(nbrs), weights=wts, k=1)[0]
        yield node

@rossbar

rossbar commented Feb 9, 2026

Copy link
Copy Markdown
Contributor

This does look interesting/effective/flexible... Something like:

Agreed - the flexibility of the generator approach, especially in terms of termination condition, is really appealing!

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Thanks for the solid pointers @rossbar, I will update the PR soon.

@NeelMishra

NeelMishra commented Feb 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @rossbar and @dschult for the review guidance, especially around simplifying the API and moving to a generator based design.

I implemented that direction by renaming to random_walk, requiring start, and switching to a generator that yields one node per step and stops naturally when no valid transition exists. I also simplified weighted handling into a single path for weighted and unweighted cases, and kept multigraph support out of scope for now, and updated tests/docs to match the new behavior.

Also attaching screenshot of the passed test cases for reference.

image

@NeelMishra
NeelMishra requested a review from rossbar February 14, 2026 02:21
@NeelMishra

Copy link
Copy Markdown
Contributor Author

Not sure how to rectify these issues though..

image

@rossbar

rossbar commented Feb 14, 2026

Copy link
Copy Markdown
Contributor

Not sure how to rectify these issues though..

Merging with main should do the trick!

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @NeelMishra , this is definitely headed in the right direction! See the inline comment re: the implementation. One final semantics question: should the start node be included in the walk? My gut feeling is that it should for consistency with how paths are treated.

Comment thread networkx/algorithms/walks.py Outdated
Comment on lines +116 to +139
current = start
while True:
neighbours = G[current]
if not neighbours:
return

# Sample using a single weighted path for both weighted and unweighted
# random walks (when weight is None, each edge weight is 1).
weight_map = {}
for neighbor, edge_data in neighbours.items():
total = 1 if weight is None else edge_data.get(weight, 1)
if total < 0:
raise ValueError(
f"Edge ({current}, {neighbor}) has negative weight {total}"
)

if total > 0:
weight_map[neighbor] = total

if not weight_map:
return

current = weighted_choice(weight_map, seed)
yield current

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think @dschult 's suggestion is even more readable (and will be faster due to accessing the underlying dict directly with G._adj) - so let's go with that. Re: checking for negative weights - we do need to do so as random.choices only checks that the sum of weights is not negative. So @dschult 's suggestion might be slightly modified with something like:

if weight is not None:
    wts = nbr.get(weight, 1) for nbr in nbrs.values()
    if any(w < 0 for w in wts):
        raise ValueError(...)
else:
    wts = None

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rossbar Yes agreed, I have incorporated this suggestion in the latest update.

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Thanks @NeelMishra , this is definitely headed in the right direction! See the inline comment re: the implementation. One final semantics question: should the start node be included in the walk? My gut feeling is that it should for consistency with how paths are treated.

In graph theory, a walk is a node sequence v0, v1, ...; v0 is part of the walk. Here v0 is a start, sorry for the miss. I think it should be included in the walk, I will update the PR.

… change from total -> edge_weight for better readability
@NeelMishra
NeelMishra requested a review from rossbar February 14, 2026 17:43
@dschult

dschult commented Feb 15, 2026

Copy link
Copy Markdown
Member

@NeelMishra can you merge this branch with the main branch? git ch main; git pull upstream main; git ch feature-request-randomwalk-algorithms; git merge main Or many other variations.
If you prefer, I can do it through github (maybe you can too -- I'm not sure). That would update the PR branch on your fork. You would then need to pull those changes to your local repo before making another commit.

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Thanks @dschult I have merged the latest main into this branch and pushed.

Comment thread networkx/algorithms/walks.py Resolved
Comment thread networkx/algorithms/tests/test_walks.py Resolved
Comment thread networkx/algorithms/tests/test_walks.py Resolved
Comment thread networkx/algorithms/tests/test_walks.py Resolved
Comment thread networkx/algorithms/walks.py Outdated
if not positive_weights:
return

current = weighted_choice(positive_weights, seed)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see here that you are avoiding using seed.choices by using nx.utils.weighted_choice. Do you think it is a reasonable approach? Is it about the same performance?

I would hope people could just contribute code that uses choices. Perhaps if the tests used Generators instead of RandomState it would work. Still interested in whether there is a difference in performance though. :)

I wonder what fraction of people use RandomState still.... :)

@NeelMishra NeelMishra Feb 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran a microbenchmark on the weighted selection step only, with fixed weights and seed, 50000 iterations, best of 10 runs.

On my machine, random.Random + choices took 5.46 micro sec per loop, while random.Random + weighted_choice took 9.15 micro sec per loop. The legacy RandomState wrapper + weighted_choice took 9.49 micro sec per loop.

Based on this, choices is faster on the random.Random path. I will change this to choices in the latest commit.

Benchmark result :

image

Code for the benchmark


import random
import time

import numpy as np
from networkx.utils.misc import create_py_random_state
from networkx.utils.random_sequence import weighted_choice

N = 50000
R = 10

m = {i: i + 1 for i in range(256)}
p = list(m)
w = list(m.values())


def bench(fn):
    runs = []
    for _ in range(R):
        t0 = time.time()
        fn()
        runs.append(time.time() - t0)
    return min(runs) * 1_000_000 / N


def random_weighted_choice():
    s = random.Random(1)
    for _ in range(N):
        weighted_choice(m, s)


def random_choices():
    s = random.Random(1)
    for _ in range(N):
        s.choices(p, weights=w, k=1)[0]


def randomstate_weighted_choice():
    s = create_py_random_state(np.random.RandomState(1))
    for _ in range(N):
        weighted_choice(m, s)


cases = [
    ("random.Random + weighted_choice", random_weighted_choice),
    ("random.Random + choices", random_choices),
    ("RandomState wrapper + weighted_choice", randomstate_weighted_choice),
]

for name, fn in cases:
    print(name)
    print(f"  {N} loops, best of {R}: {bench(fn):.2f} usec per loop")
    print()

@NeelMishra
NeelMishra requested a review from dschult February 15, 2026 23:16
@NeelMishra

Copy link
Copy Markdown
Contributor Author

@dschult , Thanks for the review, I have updated my PR with your suggestions.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One more request: we've got both "neighbor" and "neighbours" in the same function.
NetworkX style is to use the american spelling : neighbor(s)

I will also make a plug for using nbrs and nbr as no other word could abbreviate to nbr, it is shorter and it avoids any annoyance for those used to neighbour.
But that's up to you. Similar very picky point. "current" doesn't designate what the object is -- just it's time relevance. Do we need time relevance? How about "node"?

I'm ready to approve this PR.

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Hi @dschult , I have renamed the variables.

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Not sure why the check got cancelled..

@NeelMishra
NeelMishra requested a review from dschult February 16, 2026 14:27

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am going to go ahead and approve this PR - there are still quite a few things that need/can/should be addressed, but I think it will be more productive to handle those in follow-up PRs (and this has enough attention on it that it won't slip through the cracks, at least not for me!)

Thanks @NeelMishra for the proposal and working so diligently through all the reviews!

@NeelMishra

Copy link
Copy Markdown
Contributor Author

Thanks @rossbar for approving the PR, and also a big thanks to you and @dschult for guiding me throughout the PR. This was super fun, and I look forward to contribute more to networkx on similar domains.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

And there's obviously more available to do surrounding this. :)

@dschult
dschult merged commit 7918370 into networkx:main Feb 17, 2026
94 of 104 checks passed
@dschult dschult added this to the 3.7 milestone Feb 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

4 participants