Search code examples
pythonnodesnetworkxgraph-theorynodelist

Networkx: NetworkXException: nodelist contains duplicate for stochastic_block_model


I'm new to networkx (version 2.4) and a bit puzzled by the error that I get for stochastic_block_model when I try to add a nodelist. I'm trying to have a different color attribute for each block in the network using this code:

import networkx as nx
N_p = 10
N_n = 10
N_0 = 30
sizes = [N_p, N_n, N_0]
probs = [[0.25, 0.05, 0.02],
         [0.05, 0.35, 0.07],
         [0.02, 0.07, 0.40]]
nodelist = ['blue' for i in range(N_p)]
nodelist.extend(['red' for i in range(N_n)])
nodelist.extend(['green' for i in range(N_0)])
G = nx.stochastic_block_model(sizes, probs,nodelist=nodelist, seed=0,directed=1)

But I get the following error message:

...
/opt/anaconda3/lib/python3.7/site-packages/networkx/generators/community.py in stochastic_block_model(sizes, p, nodelist, seed, directed, selfloops, sparse)
    576             raise nx.NetworkXException("'nodelist' and 'sizes' do not match.")
    577         if len(nodelist) != len(set(nodelist)):
--> 578             raise nx.NetworkXException("nodelist contains duplicate.")
    579     else:
    580         nodelist = range(0, sum(sizes))

NetworkXException: nodelist contains duplicate.

What am I doing wrong?


Solution

  • The error is just that - the nodelist contains duplicates:

    >>> nodelist
    ['blue'*10, 'red'*10, 'green'*30]
    

    As in your documentation link:

    Raises NetworkXError –

    If probabilities are not in [0,1]. If the probability matrix is not square (directed case). If the probability matrix is not symmetric (undirected case). If the sizes list does not match nodelist or the probability matrix. If nodelist contains duplicate.

    To fix this, either don't use a nodelist, or do something like the following:

    nodelist = [f'blue_{i}' for i in range(N_p)]
    nodelist.extend([f'red_{i}' for i in range(N_n)])
    nodelist.extend([f'green_{i}' for i in range(N_0)])