Random Walk on Graph with Weighted Selection

  • Share this:

Code introduction


The function performs a random walk on a given graph starting from a specified node for a given number of steps. At each step, it randomly selects the next node from the neighbors of the current node based on a weight.


Technology Stack : Igraph

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(graph, steps):
    """
    Perform a random walk on the graph starting from a specified node for a given number of steps.
    """
    from igraph import Graph

    if not isinstance(graph, Graph):
        raise TypeError("graph must be an instance of igraph.Graph")

    if not isinstance(steps, int) or steps <= 0:
        raise ValueError("steps must be a positive integer")

    current_node = graph.vcount() // 2  # Start from the middle node for simplicity
    walk = [current_node]

    for _ in range(steps):
        neighbors = graph.neighbors(current_node)
        if neighbors:
            current_node = neighbors[graph.vs[current_node]['weight'] % len(neighbors)]
        walk.append(current_node)

    return walk                
              
Tags: