#NEWLINE# def double_edge_swap( G , nswap = 1 , max_tries = 100 ) : #NEWLINE# #INDENT# 'Swap two edges in the graph while keeping the node degrees fixed.\n\n    A double-edge swap removes two randomly chosen edges u-v and x-y\n    and creates the new edges u-x and v-y::\n\n     u--v            u  v\n            becomes  |  |\n     x--y            x  y\n\n    If either the edge u-x or v-y already exist no swap is performed\n    and another attempt is made to find a suitable edge pair.\n\n    Parameters\n    ----------\n    G : graph\n       An undirected graph\n\n    nswap : integer (optional, default=1)\n       Number of double-edge swaps to perform\n\n    max_tries : integer (optional)\n       Maximum number of attempts to swap edges\n\n    Returns\n    -------\n    G : graph\n       The graph after double edge swaps.\n\n    Notes\n    -----\n    Does not enforce any connectivity constraints.\n\n    The graph G is modified in place.\n    ' #NEWLINE# if G . is_directed ( ) : #NEWLINE# #INDENT# raise nx . NetworkXError ( 'double_edge_swap() not defined for directed graphs.' ) #NEWLINE# #UNINDENT# if ( nswap > max_tries ) : #NEWLINE# #INDENT# raise nx . NetworkXError ( 'Number of swaps > number of tries allowed.' ) #NEWLINE# #UNINDENT# if ( len ( G ) < 4 ) : #NEWLINE# #INDENT# raise nx . NetworkXError ( 'Graph has less than four nodes.' ) #NEWLINE# #UNINDENT# n = 0 #NEWLINE# swapcount = 0 #NEWLINE# ( keys , degrees ) = zip ( * G . degree ( ) ) #NEWLINE# cdf = nx . utils . cumulative_distribution ( degrees ) #NEWLINE# while ( swapcount < nswap ) : #NEWLINE# #INDENT# ( ui , xi ) = nx . utils . discrete_sequence ( 2 , cdistribution = cdf ) #NEWLINE# if ( ui == xi ) : #NEWLINE# #INDENT# continue #NEWLINE# #UNINDENT# u = keys [ ui ] #NEWLINE# x = keys [ xi ] #NEWLINE# v = random . choice ( list ( G [ u ] ) ) #NEWLINE# y = random . choice ( list ( G [ x ] ) ) #NEWLINE# if ( x == y ) : #NEWLINE# #INDENT# continue #NEWLINE# #UNINDENT# if ( ( x not in G [ u ] ) and ( y not in G [ v ] ) ) : #NEWLINE# #INDENT# G . add_edge ( u , x ) #NEWLINE# G . add_edge ( v , y ) #NEWLINE# G . remove_edge ( u , v ) #NEWLINE# G . remove_edge ( x , y ) #NEWLINE# swapcount += 1 #NEWLINE# #UNINDENT# if ( n >= max_tries ) : #NEWLINE# #INDENT# e = ( ( 'Maximum number of swap attempts (%s) exceeded ' % n ) + ( 'before desired swaps achieved (%s).' % nswap ) ) #NEWLINE# raise nx . NetworkXAlgorithmError ( e ) #NEWLINE# #UNINDENT# n += 1 #NEWLINE# #UNINDENT# return G