#NEWLINE# @ require ( 'numpy' ) #NEWLINE# @ not_implemented_for ( 'directed' ) #NEWLINE# def laplacian_matrix( G , nodelist = None , weight = 'weight' ) : #NEWLINE# #INDENT# "Return the Laplacian matrix of G.\n\n    The graph Laplacian is the matrix L = D - A, where\n    A is the adjacency matrix and D is the diagonal matrix of node degrees.\n\n    Parameters\n    ----------\n    G : graph\n       A NetworkX graph\n\n    nodelist : list, optional\n       The rows and columns are ordered according to the nodes in nodelist.\n       If nodelist is None, then the ordering is produced by G.nodes().\n\n    weight : string or None, optional (default='weight')\n       The edge data key used to compute each value in the matrix.\n       If None, then each edge has weight 1.\n\n    Returns\n    -------\n    L : NumPy matrix\n      The Laplacian matrix of G.\n\n    Notes\n    -----\n    For MultiGraph/MultiDiGraph, the edges weights are summed.\n    See to_numpy_matrix for other options.\n\n    See Also\n    --------\n    to_numpy_matrix\n    normalized_laplacian_matrix\n    " #NEWLINE# import numpy as np #NEWLINE# if ( nodelist is None ) : #NEWLINE# #INDENT# nodelist = G . nodes ( ) #NEWLINE# #UNINDENT# if G . is_multigraph ( ) : #NEWLINE# #INDENT# A = np . asarray ( nx . to_numpy_matrix ( G , nodelist = d , weight = weight ) ) #NEWLINE# I = np . identity ( A . shape [ 0 ] ) #NEWLINE# D = ( I * np . sum ( A , axis = 1 ) ) #NEWLINE# L = ( D - A ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# n = len ( nodelist ) #NEWLINE# index = dict ( ( ( n , i ) for ( i , n ) in enumerate ( nodelist ) ) ) #NEWLINE# L = np . zeros ( ( n , n ) ) #NEWLINE# for ( ui , u ) in enumerate ( nodelist ) : #NEWLINE# #INDENT# totalwt = 0.0 #NEWLINE# for ( v , d ) in G [ u ] . items ( ) : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# vi = index [ v ] #NEWLINE# #UNINDENT# except KeyError : #NEWLINE# #INDENT# continue #NEWLINE# #UNINDENT# wt = d . get ( weight , 1 ) #NEWLINE# L [ ( ui , vi ) ] = ( - wt ) #NEWLINE# totalwt += wt #NEWLINE# #UNINDENT# L [ ( ui , ui ) ] = totalwt #NEWLINE# #UNINDENT# #UNINDENT# return np . asmatrix ( L )