def test_laplacian_spectrum(self):
     "Laplacian eigenvalues"
     evals=numpy.array([0, 0, 1, 3, 4])
     e=sorted(nx.laplacian_spectrum(self.G))
     assert_almost_equal(e,evals)
     e=sorted(nx.laplacian_spectrum(self.WG,weight=None))
     assert_almost_equal(e,evals)
     e=sorted(nx.laplacian_spectrum(self.WG))
     assert_almost_equal(e,0.5*evals)
     e=sorted(nx.laplacian_spectrum(self.WG,weight='other'))
     assert_almost_equal(e,0.3*evals)
def algebraic_connectivity_of_graph(graph):
    if not graph:
        return 0.0
    ls = sorted(nx.laplacian_spectrum(graph))
    # Is the graph connected?
    if (ls[1] - ls[0]) > 1e-10:
        return ls[1]
    else: return 0.0
Esempio n. 3
0
def investigate_laplacian(graph):
    """ Compute Laplacian
    """
    w = nx.laplacian_spectrum(graph)

    pairs = []
    for i, w in enumerate(sorted(w)):
        if abs(w) < 1e-5: continue
        inv_w = 1 / w
        pairs.append((inv_w, i))

    fig = plt.figure()
    plt.scatter(*zip(*pairs))
    plt.xlabel(r'$\frac{1}{\lambda_i}$')
    plt.ylabel(r'rank index')
    save(fig, 'laplacian_spectrum')
def eigenvalueAttributes(graph):
	return_values = []
	#Compute eigenvalues on L as ndarray object
	#L = nx.normalized_laplacian_matrix(graph) #numpy matrix
	#e = numpy.linalg.eigvals(L.A) #takes matrix and returns eigenvalues
	e = nx.laplacian_spectrum(graph) #numPy array; uses unnormalized laplcian matrix
	#e = nx.adjacency_spectrum(graph) #numPy array
	eig_sum = 0
	largest = 0
	second_largest = 0
	unique_values = []
	inverse_product = 1
	for i in e:
		if i < 0:
			abs_i = i * -1
		else:
			abs_i = i
		#woods midterm paper - use squared sum of abs value
		eig_sum += abs_i
		#eigenvalue distriminants paper - use inverse of product of sqrt(|eigval|)
		inverse_product *= math.sqrt(abs_i) 
		if i not in unique_values:
			unique_values.append(i)
	#energy: squared sum of eigenvalues
	return_values.append(eig_sum*eig_sum)
	largest = max(e) 
	l_index = numpy.argmax(e)
	e = numpy.delete(e, l_index)
	#Second largest eigenvalue (actual value, not magnitude)
	second_largest = max(e)
	return_values.append(second_largest)
	#Number distict eigenvalues
	return_values.append(len(unique_values))
	#Spectral Radius: largest eigenvalue (actual value, not magnitude)
	return_values.append(largest)
	#Inverse product [1/(sqrt|eig1| * sqrt|eig2| * ... * sqrt|eign|)]
	if(inverse_product > 0):
		return_values.append(1/inverse_product)
	else:
		return_values.append(0)
	return return_values
Esempio n. 5
0
 print "assortativity.average_degree_connectivity",'\t\t', nx.assortativity.average_degree_connectivity(graphs[g])
 #print "degree_pearson_correlation_coefficient",'\t\t', nx.degree_pearson_correlation_coefficient(graphs[g])
 print "node closeness_centrality",'\t\t\t', get_avg(nx.closeness_centrality(graphs[g]))
 print "clustering",'\t\t\t', get_avg(nx.clustering(graphs[g]))
 print "node betweeness",'\t\t\t', get_avg(nx.betweenness_centrality(graphs[g],normalized=False,endpoints=False))
 print "edge betweeness",'\t\t\t', get_avg(nx.edge_betweenness_centrality(graphs[g],normalized=False))
 #print "spectral_bipartivity",'\t\t', bipartite.spectral_bipartivity(graphs[g])
 #print "node betweeness normalized",'\t\t\t', get_avg(nx.betweenness_centrality(graphs[g],normalized=True,endpoints=False))
 #print "edge betweeness normalized",'\t\t\t', get_avg(nx.edge_betweenness_centrality(graphs[g],normalized=True))
 #print "node closeness_vitality",'\t\t\t', get_avg(nx.closeness_vitality(graphs[g]))
 #print "communicability_centrality",'\t\t', get_avg(nx.communicability_centrality(graphs[g]))
 #print "communicability_betweenness_centrality",'\t\t', get_avg(nx.communicability_betweenness_centrality(graphs[g]))
 #print "transitivity",'\t\t\t', round(nx.transitivity(graphs[g]),4)
 #print "laplacian_spectrum",'\t\t\n:', nx.laplacian_spectrum(graphs[g])
 print "adjacency_spectrum",'\t\tMin 5 :', get_min(nx.adjacency_spectrum(graphs[g])) , "\t\tMax 5 :",get_max(nx.adjacency_spectrum(graphs[g]))
 print "laplacian_spectrum",'\t\tMin 5 :', get_min(nx.laplacian_spectrum(graphs[g])) , "\t\tMax 5 :",get_max(nx.laplacian_spectrum(graphs[g])) 
 #print "normalized_laplacian_spectrum",'\t\tMin 5 :', get_min(numpy.real(normalized_laplacian_spectrum(graphs[g]))) , "\t\tMax 5 :",get_max(normalized_laplacian_spectrum(graphs[g]))
 #print "adjacency_spectrum",'\t\t\n', nx.adjacency_spectrum(graphs[g])
 #print "laplacian_spectrum",'\t\t\n', nx.laplacian_spectrum(graphs[g])
 #print "normalized_laplacian_spectrum",'\t\t\n', normalized_laplacian_spectrum(graphs[g])
 ####print "adjacency_spectrum",'\t\t\n', numpy.around(numpy.real(nx.adjacency_spectrum(graphs[g])), decimals=4)
 ####print "laplacian_spectrum",'\t\t\n', numpy.around(numpy.real(nx.laplacian_spectrum(graphs[g])), decimals=4)
 ####print "normalized_laplacian_spectrum",'\t\t\n', numpy.around(numpy.real(normalized_laplacian_spectrum(graphs[g])), decimals=4)
 #statistics.pdf_to_textfile(numpy.real(numpy.around(nx.adjacency_spectrum(graphs[g]), decimals=2)).tolist(),g+"_adj_pdf.txt")
 # Write to a file
 #statistics.to_textfile(numpy.real(numpy.around(nx.adjacency_spectrum(graphs[g]), decimals=2)).tolist(),g+"_adj_pdf.txt")
 #statistics.pdf_to_textfile(numpy.real(numpy.around(nx.laplacian_spectrum(graphs[g]), decimals=2)).tolist(),g+"_pdf.txt")
 #statistics.cdf_to_textfile(numpy.real(numpy.around(nx.laplacian_spectrum(graphs[g]), decimals=2)).tolist(),g+"_cdf.txt")
 #statistics.pdf_to_textfile(numpy.real(numpy.around(normalized_laplacian_spectrum(graphs[g]), decimals=4)).tolist(),g+"_pdf.txt")
 #statistics.cdf_to_textfile(numpy.real(numpy.around(normalized_laplacian_spectrum(graphs[g]), decimals=4)).tolist(),g+"_cdf.txt")
 #print "adjacency_matrix",'\t\t\t\n', nx.adjacency_matrix(graphs[g])
def lapl_spect(net):
    spec = nx.laplacian_spectrum(net)
    connec = sorted(spec)[1]
    _,b,c,d = spectrum(spec,'laplacian')
    return b,c,d,(connec,'algebraic_connectivity')
Esempio n. 7
0
def creationVecteur (G):
    v={}
    # Adding nodes
    nn = nx.number_of_nodes(G)
    v["numNodes"]=nn
    
    # Adding edges
    ne = nx.number_of_edges(G)
    v["numEdges"]=ne
    
    # Adding cyclomatic number
    c=nx.number_connected_components(G)
    cyclo = ne-nn+c
    v["numCycles"]=cyclo
    
    # Adding link density
    if nn==1:
        linkdensity="?"
    else:
        linkdensity = 2*ne/((nn-1)*nn)
    v["linkDensity"]=linkdensity
    
    # Adding average degree
    avgdegree = 2*ne/nn
    v["avgDegree"]=avgdegree
    
    # Adding number of leaves
    nl = numberLeaves(G)
    v["numLeafs"]=nl
    
    # Adding histogram of the nodes degree
    v["histDegree0"]=0
    v["histDegree1"]=0
    v["histDegree2"]=0
    v["histDegree3"]=0
    v["histDegree4"]=0
    histDegree=nx.degree_histogram(G)
    v["histDegree0"]=histDegree[0]
    if len(histDegree)>1:
        v["histDegree1"]=histDegree[1]
        if len(histDegree)>2:
            v["histDegree2"]=histDegree[2]
            if len(histDegree)>3:
                v["histDegree3"]=histDegree[3]
                if len(histDegree)>4:
                    v["histDegree4"]=histDegree[4]
  
    # Adding sMetric
    v["sMetric"]= metric(G)
    
    # Adding graph energy
    energ = graphEnergy (G)
    v["graphEnergy"]=energ     
    
    # Adding average of the average neighboring degrees of all nodes
    av = averageNeighDegree(G)
    v["averageNeighDegree"]=av
    
    # Adding average of closeness over all nodes
    v["averageCloseness"]=average_closeness(G)
    
    # Adding pearson coefficient for the degree sequence of all edges of the graph
    pearson = nx.degree_pearson_correlation_coefficient(G)
    if np.isnan(pearson):
        pearson = 0 
    v["pearson"]=pearson

    # Adding rich club metric for all nodes with a degree larger than 1
    rc=richClub(G)
    v["richClub"]=rc
    
    # Adding algebraic connectivity, i.e. the second smallest eigenvalue of the Laplacian
    algConnect = nx.laplacian_spectrum(G)
    algConnect = list(algConnect)
    algConnect = sorted(algConnect)
    v["algConnect"]=algConnect[1]
    
    # Adding diameter of the graph
    if nx.is_connected(G):
        diam = nx.diameter(G)
    
    else:
        diam="?"
    v["diameter"]=diam

    # Adding average shortest path
    if nx.is_connected(G):
        avgShortestPath=nx.average_shortest_path_length(G)
    
    else:
        avgShortestPath="?"
    v["avgShortPath"]=avgShortestPath
    
    # Adding graph radius
    if nx.is_connected(G):
        rad = nx.radius(G)
    else:
        rad="?"
    v["graphRadius"]=rad

    return v
    # but for the 2010 connection algorithm there shouldn't be any
    # multiedge in the graph
    for k, cell_pair_list in enumerate(cell_pair_lol):
        assert len(cell_pair_list)==len(ordered_edge_lists[k])
    graphs = [nx.empty_graph(n_cells, create_using=nx.Graph()) for each in cell_pair_lol]
    for k,g in enumerate(graphs):
        g.add_edges_from(cell_pair_lol[k])
        nx.write_graphml(g, '../dataSets/graphs/graph_2010_ncells{0}_trial{1:02}.graphml'.format(n_cells, k))

    average_clustering_coefficients = np.array([nx.average_clustering(g) for g in graphs])
    print("Average clustering: {0} ± {1}".format(average_clustering_coefficients.mean(),
                                                 np.sqrt(average_clustering_coefficients.var())))
    average_shortest_path_lengths = np.array([nx.average_shortest_path_length(g) for g in graphs])
    print("Average shortest path length: {0} ± {1}".format(average_shortest_path_lengths.mean(),
                                                           np.sqrt(average_shortest_path_lengths.var())))
    laplacian_spectra = [np.sort(nx.laplacian_spectrum(g)) for g in graphs]
    eigenratios = np.array([s[-1]/(s[2]) for s in laplacian_spectra])
    print("Average eigenratio: {0} ± {1}".format(eigenratios.mean(),
                                                 np.sqrt(eigenratios.var())))
    # for each trial, calculate the degree sequence of the
    # network. Note that the degree of a cell is defined as the number
    # of unique cells it's connected to; the number of gap junctions
    # on a cell is an obvious upper bound for the cell's degree.
    degree_sequences = np.array([[len([pair for pair in l if any((pair[0]==k, pair[1]==k))]) for k in range(n_cells)] for l in cell_pair_lol])
    # for each trial, for each connected pair, calculate the distance
    # between somata
    edge_lengths = []
    for trial, cell_pair_list in enumerate(cell_pair_lol):
        lengths = np.array([distances_squareform[trial][tuple(e)] for e in cell_pair_list])
        edge_lengths.append(lengths)
 def test_laplacian_spectrum(self):
     "Laplacian eigenvalues"
     evals=numpy.array([0, 0, 1, 3, 4])
     e=sorted(nx.laplacian_spectrum(self.G))
     assert_almost_equal(e,evals)
Esempio n. 10
0
    def _compute(self, graph):
        s = nx.laplacian_spectrum(graph)

        return s
Esempio n. 11
0
 def ComputeLaplacianMatrixEigenvalues(self):
     self.laplacianSpectrum =  np.around(np.array(nx.laplacian_spectrum(self.G)),decimals=4)
     self.laplacianSpectrum.sort()
Esempio n. 12
0
'''
Theorem 3 of

Mahadevan, S., & Maggioni, M. (2007). Proto-value functions: A Laplacian
framework for learning representation and control in Markov decision
processes. Journal of Machine Learning Research, 8

states that the eigenvalues of the Laplacian of graph G that is the cartesian
product of two graphs G1 and G2, are the sums of all the combination of the
eigenvalues of G1 and G2.

This program illustrates this by generating a grid as the cartesian product of
two paths.
'''

from itertools import product
import networkx as nx

n = 5
P = nx.path_graph(n)
G = nx.cartesian_product(P, P)

ev_P = nx.laplacian_spectrum(P)
ev_G = nx.laplacian_spectrum(G).real

ev = []
for i,j in product(range(n), repeat=2):
    ev.append(ev_P[i] + ev_P[j])


Esempio n. 13
0
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt


G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3), (2, 3), (1, 4), (4, 5)])
G2 = nx.generators.random_graphs.fast_gnp_random_graph(10, .3)
# nx.adjacency_matrix(G)
L = nx.laplacian(G)  # L=D-A
# np.linalg.eigvals(L)
np.linalg.eig(L)
res = nx.laplacian_spectrum(G)
print res

print nx.normalized_laplacian(G)
c = nx.communicability(G)

# drawing
nx.draw(G)  # default using spring_layout: force-directed
# same as:
# pos = nx.spring_layout(G)
# nx.draw(G, pos)
nx.draw_random(G)
nx.draw_spectral(G)
plt.show()
plt.savefig('path.png')
plt.cla()

# random graph
G = nx.generators.random_graphs.random_regular_graph(6, 50)