コード例 #1
0
 def SwapNodes(self, swapNodes):
     for (nodeX, nodeY) in swapNodes:
         self.amends += 1
         self.partition[0].remove(nodeX)
         self.partition[0].append(nodeY)
         self.partition[1].remove(nodeY)
         self.partition[1].append(nodeX)
         #print(self.partition)
         #time.sleep(20)
         #self.G=nx.relabel_nodes(self.G,
         #mapping={nodeX:nodeY,nodeY:nodeX})
         self.components[0] = self.G.subgraph(self.partition[0]).copy()
         self.components[1] = self.G.subgraph(self.partition[1]).copy()
         self.spectrum = nx.laplacian_spectrum(self.G)
         self.algebraic_connectivity = nx.algebraic_connectivity(self.G)
         self.components_spectrum[0] = nx.laplacian_spectrum(
             self.components[0])
         self.components_spectrum[1] = nx.laplacian_spectrum(
             self.components[1])
         self.components_ac[0] = nx.algebraic_connectivity(
             self.components[0])
         self.components_ac[1] = nx.algebraic_connectivity(
             self.components[1])
         self.history.append([
             self.algebraic_connectivity, self.components_ac[0],
             self.components_ac[1]
         ])
         logging.info("Changes appended to history succesfully.")
コード例 #2
0
ファイル: s3det.py プロジェクト: zhuhanqing/SymDetect
def graph_sim(g1, g2, tol):
    """ determine subgraph similarity
    """
    spec1 = nx.laplacian_spectrum(g1)
    spec2 = nx.laplacian_spectrum(g2)
    D, p_val = ks_2samp(spec1, spec2)
    return p_val >= tol
コード例 #3
0
ファイル: GraphSim.py プロジェクト: sethupathib/MAGICAL
 def specSimScore(self, subgraphA, subgraphB, centerType=None):
     self.defSub(subgraphA, subgraphB)
     self.extractSub(centerType)
     specA = nx.laplacian_spectrum(self.extA, weight=None)
     specB = nx.laplacian_spectrum(self.extB, weight=None)
     D, p_val = stat.ks_2samp(specA, specB)
     return p_val
コード例 #4
0
 def getSimilarity(self):
     laplacian1 = nx.laplacian_spectrum(self.graph1)
     laplacian2 = nx.laplacian_spectrum(self.graph2)
     k1 = select_k(laplacian1)
     k2 = select_k(laplacian2)
     k = min(k1, k2)
     similarity = sum((laplacian1[:k] - laplacian2[:k]) ** 2)
     if similarity == 0:
         similarity = 1
     return similarity
コード例 #5
0
 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)
コード例 #6
0
ファイル: test_spectrum.py プロジェクト: ynux/networkx
 def test_laplacian_spectrum(self):
     "Laplacian eigenvalues"
     evals = numpy.array([0, 0, 1, 3, 4])
     e = sorted(nx.laplacian_spectrum(self.G))
     npt.assert_almost_equal(e, evals)
     e = sorted(nx.laplacian_spectrum(self.WG, weight=None))
     npt.assert_almost_equal(e, evals)
     e = sorted(nx.laplacian_spectrum(self.WG))
     npt.assert_almost_equal(e, 0.5 * evals)
     e = sorted(nx.laplacian_spectrum(self.WG, weight='other'))
     npt.assert_almost_equal(e, 0.3 * evals)
コード例 #7
0
def get_laplacian(graph, graph_name):
    """
        Graph laplacian maxtrix eigen values와 normalizaed 된 값을 구한다.
    """

    eigen_values = nx.laplacian_spectrum(graph)
    print('eigen values of ' + graph_name + ' ' +
          ', '.join(["{0:0.4f}".format(i) for i in eigen_values[:10]]) +
          "    min eigenvalue {0:0.4f}, max eigenvalue {1:0.4f}".format(
              min(eigen_values), max(eigen_values)))

    nor_lapla_mx = nx.normalized_laplacian_matrix(graph)
    n_eigen_values = np.sort(np.linalg.eigvals(nor_lapla_mx.A))

    print('nor eigen values of ' + graph_name + ' ' +
          ', '.join(["{0.real:.4f}".format(i) for i in n_eigen_values[:10]]) +
          "  min eigenvalue {0.real:.4f}, max eigenvalue {1.real:.4f}".format(
              min(n_eigen_values), max(n_eigen_values)))
    print("Clustering Coefficient " + graph_name + ' ' +
          ": {0}".format(nx.clustering(graph)))
    print("Avg. Clustering Coefficient " + graph_name + ' ' +
          ": {0:.4f}".format(nx.average_clustering(graph)))
    print("Transivity of " + graph_name + ' ' +
          "{0:.4f} : ".format(nx.transitivity(graph)))
    print("####################################")
コード例 #8
0
ファイル: feature_augment.py プロジェクト: tapasag/GraphGym
 def graph_laplacian_spectrum_fun(graph, **kwargs):
     # first eigenvalue is 0
     spectrum = nx.laplacian_spectrum(graph.G)[1:]
     feature_dim = kwargs['feature_dim']
     if len(spectrum) > feature_dim:
         spectrum = spectrum[:feature_dim]
     return torch.tensor(spectrum)
コード例 #9
0
def get_laplacian_spectrum(graph, k=np.inf, which='SM', tol=1E-2, eigvals_only=True, use_gpu=False):
    """
    Gets the bottom k eigenpairs of the Laplacian matrix

    :param graph: undirected NetworkX graph
    :param k: number of bottom k eigenpairs to obtain
    :param which:  he type of k eigenvectors and eigenvalues to find
    :param tol: the precision at which to stop computing the eigenpairs
    :param eigvals_only: get only the eigenvalues i.e., no eigenvectors

    :return: the eigenpair information
    """

    if use_gpu: print('Warning: GPU requested, but not available for Laplacian measures')

    # get all eigenvalues for small graphs
    if len(graph) < 100:
        lam = nx.laplacian_spectrum(graph)
    else:
        L = get_laplacian(graph)
        lam = eigsh(L, k=min(k, len(graph) - 1), which=which, tol=tol, return_eigenvectors=not eigvals_only)

    lam = np.sort(lam)  # sort ascending

    return lam
コード例 #10
0
ファイル: graph_features.py プロジェクト: KevinHoarau/BML
 def computeFeatures(self, G, features_nx, features_nk):
 
     if("effective_graph_resistance" in features_nx or "nb_spanning_trees" in features_nx or "algebraic_connectivity" in features_nx):
         if(self.params["verbose"]):
             print("Computing laplacian_eigenvalues")
             s = time.time()
         self.eigenvalues["laplacian"] = np.real(nx.laplacian_spectrum(G))
         if(self.params["verbose"]):
             print("Finish laplacian_eigenvalues (%s)" % (timeFormat(time.time()-s)))
             
     if("largest_eigenvalue" in features_nx or "symmetry_ratio" in features_nx or "natural_connectivity" in features_nx):
         if(self.params["verbose"]):
             print("Computing adjacency_eigenvalues")
             s = time.time()
         self.eigenvalues["adjacency"] = np.real(nx.adjacency_spectrum(G))
         if(self.params["verbose"]):
             print("Finish adjacency_eigenvalues (%s)" % (timeFormat(time.time()-s)))
             
     if("weighted_spectrum_3" in features_nx or "weighted_spectrum_4" in features_nx):
         if(self.params["verbose"]):
             print("Computing normalized_laplacian_eigenvalues")
             s = time.time()
         self.eigenvalues["normalized_laplacian"] = np.real(nx.normalized_laplacian_spectrum(G))
         if(self.params["verbose"]):
             print("Finish normalized_laplacian_eigenvalues (%s)" % (timeFormat(time.time()-s)))
     
     return(NodesFeatures.computeFeatures(self, G, features_nx, features_nk))
コード例 #11
0
	def create_graph(self):
		g = nx.Graph()
		duplicated_nodes_list = self.only_nodes.iloc[:,0].append(self.only_nodes.iloc[:,1]).reset_index(drop=True)
		nodes_list = duplicated_nodes_list.values.tolist()
		No_duplicate_nodes = set(nodes_list)
		# print(len(No_duplicate_nodes))#327
		g.add_nodes_from(No_duplicate_nodes)
		g.add_edges_from(self.No_duplicate_links)
		# nx.draw(g,node_size = 1.5)#with_labels=True
		# plt.draw()
		# plt.show()
		link_density = nx.density(g)
		# print(link_density)#0.109
		average_degree = nx.average_neighbor_degree(g)
		# numbers degreeede= [average_degree[key] for key in average_degree]
		# mean = statistics.mean(numbers)
		# var = statistics.variance(numbers)
		# print(var)
		degree_correlation = nx.degree_pearson_correlation_coefficient(g) 
		# print(degree_correlation)#0.033175769936049336
		average_clustering = nx.average_clustering(g)
		# print(average_clustering)#0.5035048191728447
		average_hopcount = nx.average_shortest_path_length(g)
		# print(average_hopcount)#2.1594341569576554
		diameter = nx.diameter(g)
		# print(diameter)#4
		# A = nx.adjacency_matrix(g)
		A_eigenvalue = nx.adjacency_spectrum(g)
		# print(max(A_eigenvalue))#(41.231605032525835+0j)
		G_eigenvalue = nx.laplacian_spectrum(g)
		# print(sorted(G_eigenvalue))#1.9300488624481513
		return g, nodes_list, No_duplicate_nodes, link_density, average_degree
コード例 #12
0
def spectralgapscore(subgraphs):
	sum = 0
	for g in subgraphs:
		S = nx.laplacian_spectrum(g)
		gap = (S[len(S) - 1] - S[len(S) - 2])/ S[len(S) - 1]
	sum = sum + gap
	return sum
コード例 #13
0
ファイル: analise_rede_CDR.py プロジェクト: itsmealves/carl
def get_statistics(graph, matrix):
    plt.figure()
    d = matrix.sum(axis=1)
    e = np.sum(d) / graph.order()
    print("Average degree: ", e)

    hist = nx.degree_histogram(graph)
    entropy = 0
    for i in range(len(hist)):
        if hist[i] != 0:
            entropy -= hist[i] * np.log2(hist[i])

    print("Entropy: ", entropy)

    # average_sp = nx.average_shortest_path_length(graph)
    # print("Average shortest path length: ", average_sp)

    average_c = nx.average_clustering(graph)
    print("Network Clustering: ", average_c)

    a_s = nx.degree_assortativity_coefficient(graph)
    print("Assortativeness: ", a_s)

    density = nx.density(graph)
    print("Density:", density)

    plt.bar(range(len(hist)), hist)
    plt.title("Degree Distribution")
    plt.xlabel("Degree")
    plt.ylabel("Number of nodes")
    plt.show()

    autovalores = nx.laplacian_spectrum(graph)
    plt.bar(range(len(autovalores)), autovalores)
    plt.title("Autovalues")
コード例 #14
0
ファイル: utils.py プロジェクト: jnowak90/CytoSeg2.0
def compute_graph(graph, nodePositions, mask):
    """Compute graph properties.

    Parameters
    ----------
    graph : original graph
    nodePositions : node positions
    mask : binary array of cellular region of interest

    Returns
    -------
    properties : list of graph properties

    """
    nodeNumber = graph.number_of_nodes()
    edgeNumber = graph.number_of_edges()
    connectedComponents = connected_components(graph)
    connectedComponentsNumber = len(connectedComponents)
    edgeCapacity = 1.0 * np.array([property['capa'] for node1, node2, property in graph.edges(data=True)])
    bundling = np.nanmean(edgeCapacity)
    assortativity = nx.degree_pearson_correlation_coefficient(graph, weight='capa')
    shortestPathLength = path_lengths(graph)
    reachability = np.nanmean(shortestPathLength)
    shortestPathLengthSD = np.nanstd(shortestPathLength)
    shortestPathLengthCV = 1.0 * shortestPathLengthSD / reachability
    algebraicConnectivity = np.sort(nx.laplacian_spectrum(graph, weight='capa'))[1]
    edgeAngles = edge_angles(graph, nodePositions, mask)
    edgeAnglesMean = np.nanmean(edgeAngles)
    edgeAnglesSD = np.nanstd(edgeAngles)
    edgeAnglesCV = 1.0 * edgeAnglesSD / edgeAnglesMean
    edgeCrossings = crossing_number(graph, nodePositions)
    edgeCrossingsMean = np.nanmean(edgeCrossings)
    properties = [nodeNumber, edgeNumber, connectedComponentsNumber, bundling, assortativity, reachability, shortestPathLengthCV, algebraicConnectivity, edgeAnglesCV, edgeCrossingsMean]
    return(properties)
コード例 #15
0
def get_laplacian_spectrum(graph,
                           k=np.inf,
                           which='SM',
                           tol=1E-2,
                           eigvals_only=True):
    """
    Gets the bottom k eigenpairs of the Laplacian matrix
    :param graph: sparse matrix
    :param k: number of bottom k eigenpairs to obtain
    :param which:  he type of k eigenvectors and eigenvalues to find
    :param tol: the precision at which to stop computing the eigenpairs
    :param eigvals_only: get only the eigenvalues i.e., no eigenvectors

    :return: the eigenpair information
    """
    # get all eigenvalues for small graphs
    if len(graph) < 100:
        lam = nx.laplacian_spectrum(graph)
    else:
        L = get_laplacian(graph)
        lam = eigsh(L,
                    k=min(k,
                          len(graph) - 1),
                    which=which,
                    tol=tol,
                    return_eigenvectors=not eigvals_only)

    lam = np.sort(lam)  # sort ascending

    return lam
コード例 #16
0
    def data_analysis(self, graph):
        data_vec = [0] * 13
        num_vertex = nx.number_of_nodes(graph)

        data_vec[0] = nx.average_clustering(graph)

        sq_values = list(nx.square_clustering(graph).values())
        data_vec[1] = sum(sq_values) / len(sq_values)

        g = nx.path_graph(num_vertex)
        data_vec[2] = nx.average_shortest_path_length(
            graph) / nx.average_shortest_path_length(g)

        data_vec[3] = nx.degree_pearson_correlation_coefficient(graph)
        if math.isnan(data_vec[3]) is True:
            data_vec[3] = 0

        data_vec[4] = nx.diameter(graph) / (num_vertex - 1)
        data_vec[5] = nx.density(graph)

        data_vec[6] = nx.edge_connectivity(graph) / (num_vertex - 1)

        g = nx.star_graph(num_vertex - 1)
        Freeman_degree_norm = self.freeman_centralization(
            nx.degree_centrality(g))
        Freeman_close_norm = self.freeman_centralization(
            nx.closeness_centrality(g))
        Freeman_between_norm = self.freeman_centralization(
            nx.betweenness_centrality(g))
        # need to change
        Freeman_eigen_norm = self.freeman_centralization(
            nx.eigenvector_centrality_numpy(g))

        data_vec[7] = self.freeman_centralization(
            nx.degree_centrality(graph)) / Freeman_degree_norm
        data_vec[8] = self.freeman_centralization(
            nx.closeness_centrality(graph)) / Freeman_close_norm
        data_vec[9] = self.freeman_centralization(
            nx.betweenness_centrality(graph)) / Freeman_between_norm

        # warning, the way it normalized may not correct
        data_vec[10] = self.freeman_centralization(
            nx.eigenvector_centrality_numpy(graph)) / Freeman_eigen_norm

        egvl_lap = nx.laplacian_spectrum(graph)
        egvl_lap = np.sort(egvl_lap)
        egvl_lap = np.delete(egvl_lap, 0, 0)
        summ = 0
        for mu in egvl_lap:
            summ += (1 / mu)

        summ = summ * num_vertex
        data_vec[11] = (num_vertex - 1) / summ

        # for simple graph(adj matrix is symmetric), eigenvalue must be real number.
        egvl_adj = np.real(nx.adjacency_spectrum(graph))
        data_vec[12] = max(egvl_adj) / (num_vertex - 1)

        return data_vec
コード例 #17
0
 def calculateSpectrum(self):
     self.components_spectrum = {}
     self.components_ac = {}
     self.spectrum = None
     self.algebraic_connectivity = 0
     self.spectrum = nx.laplacian_spectrum(self.G)
     self.algebraic_connectivity = nx.algebraic_connectivity(self.G)
     self.components_spectrum[0] = nx.laplacian_spectrum(self.components[0])
     self.components_spectrum[1] = nx.laplacian_spectrum(self.components[1])
     self.components_ac[0] = nx.algebraic_connectivity(self.components[0])
     self.components_ac[1] = nx.algebraic_connectivity(self.components[1])
     logging.info("Spectrum and algebraic connectivity values calculated.")
     self.history.append([
         self.algebraic_connectivity, self.components_ac[0],
         self.components_ac[1]
     ])
     logging.info("Appened to history succesfully.")
コード例 #18
0
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
コード例 #19
0
def LapSpectrum(G):
    """
    Calculate the eigenvalues of the Laplacian matrix of a network
    :param G: [networkx graph object] this is a networkx graph object
    :return: [list] Returns a list of the real part of the eigenvalues of the Laplacian matrix of G
    """
    eig_temp = nx.laplacian_spectrum(G)
    eig = [x.real for x in eig_temp]
    return eig
コード例 #20
0
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
コード例 #21
0
 def test_bethe_hessian_spectrum(self):
     "Bethe Hessian eigenvalues"
     evals = np.array([0.5 * (9 - np.sqrt(33)), 4, 0.5 * (9 + np.sqrt(33))])
     e = sorted(nx.bethe_hessian_spectrum(self.P, r=2))
     npt.assert_almost_equal(e, evals)
     # Collapses back to Laplacian:
     e1 = sorted(nx.bethe_hessian_spectrum(self.P, r=1))
     e2 = sorted(nx.laplacian_spectrum(self.P))
     npt.assert_almost_equal(e1, e2)
コード例 #22
0
ファイル: graph_features.py プロジェクト: KevinHoarau/BML
def algebraic_connectivity(G, nodes, eigenvalues=None):
    laplacian_eigenvalues = None
    if(not eigenvalues is None):
        laplacian_eigenvalues = eigenvalues["laplacian"]
    if(laplacian_eigenvalues is None):
        laplacian_eigenvalues = np.real(nx.laplacian_spectrum(G))
        
    laplacian_eigenvalues = np.delete(laplacian_eigenvalues, laplacian_eigenvalues.argmin())
    v = np.min(laplacian_eigenvalues)
    return(np.float64(v))
コード例 #23
0
ファイル: graph_features.py プロジェクト: KevinHoarau/BML
def effective_graph_resistance(G, nodes, eigenvalues=None):
    laplacian_eigenvalues = None
    if(not eigenvalues is None):
        laplacian_eigenvalues = eigenvalues["laplacian"]
    if(laplacian_eigenvalues is None):
        laplacian_eigenvalues = np.real(nx.laplacian_spectrum(G))
    laplacian_eigenvalues = np.delete(laplacian_eigenvalues, laplacian_eigenvalues.argmin())
    nonzero_eigenvalues = laplacian_eigenvalues[np.nonzero(laplacian_eigenvalues)]
    nst = len(G)*np.sum(1/nonzero_eigenvalues)
    return(np.float64(nst))
コード例 #24
0
ファイル: graph_features.py プロジェクト: KevinHoarau/BML
def nb_spanning_trees(G, nodes, eigenvalues=None):
    laplacian_eigenvalues = None
    if(not eigenvalues is None):
        laplacian_eigenvalues = eigenvalues["laplacian"]
    if(laplacian_eigenvalues is None):
        laplacian_eigenvalues = np.real(nx.laplacian_spectrum(G))
    laplacian_eigenvalues = np.delete(laplacian_eigenvalues, laplacian_eigenvalues.argmin())
    nonzero_eigenvalues = laplacian_eigenvalues[np.nonzero(laplacian_eigenvalues)]
    nst = np.prod(nonzero_eigenvalues/len(G))
    return(np.float64(nst))
コード例 #25
0
def draw_laplacian_spectrum(orig_g, new_g, g1_label, ax):
  """
  The set of all N Laplacian eigenvalues is called the Laplacian spectrum of a graph G. The second smallest eigenvalue is lamdaN >= 1, but equal to zero only if a graph is disconnected. Thus, the multiplicity of 0 as an eigenvalue of Q is equal to the number of components of G [8].
  """

  import matplotlib.patches as mpatches
  es = nx.laplacian_spectrum(new_g)
  ax.plot(range(new_g.number_of_nodes()), es, 'k-o', alpha=0.2)
  es = nx.laplacian_spectrum(orig_g)
  ax.plot(range(orig_g.number_of_nodes()), es, 'r-o')


  ax.set_title("Laplacian Spectrum")
  blue_patch = mpatches.Patch(color='r', label=g1_label)
  green_patch = mpatches.Patch(color='black', label="Synthetic")
  ax.legend(handles=[blue_patch, green_patch])

  # set plot to log log scale
  ax.set_yscale('log')
  ax.set_xscale('log')
コード例 #26
0
def draw_laplacian_spectrum_conf_bands(orig_g, synth_graphs, graph_name, ax):
  """
  ax = axis handle for a given figure

  Reference:
  http://stackoverflow.com/questions/27164114/show-confidence-limits-and-prediction-limits-in-scatter-plot
  """
  import matplotlib.patches as mpatches
  import pandas as pd

  eigs = [nx.laplacian_spectrum(g) for g in synth_graphs]
  df = pd.DataFrame(eigs)

  es = nx.laplacian_spectrum(orig_g)
  ax.plot(df.min(), 'k:')
  ax.plot(df.max(), 'k:')
  ax.fill_between(df.columns, df.mean()-df.quantile(.05), df.mean()+df.quantile(.95), color='b', alpha=0.2)
  if nx.__version__ == '1.10':
    ax.fill_between(df.columns, df.mean()-df.sem(), df.mean()+df.sem(), color='r', alpha=0.2)
  ax.plot(range(orig_g.number_of_nodes()), es, 'ko',alpha=0.5 )

#  ax.plot(df.quantile(.95),'r--',alpha=0.5)
#  ax.plot(df.quantile(.05),'r--',alpha=0.5)
#  ax.fill_between(df.columns, df.mean()-2*df.std(), df.mean()+2*df.std(), color='b', alpha=0.2)
#
#  ax.set_title("Laplacian Spectrum")
#  blue_patch = mpatches.Patch(color='r', label=g1_label)
#  green_patch = mpatches.Patch(color='black', label="Synthetic")
#  ax.legend(handles=[blue_patch, green_patch])

  #### AXES LABELS
  # set plot to log log scale
#  ax.set_yscale('log')
#  ax.set_xscale('log')

  ## Set
  ax.set_ylabel('Eigenvalues')
  ax.set_xlabel('Node Count')
#  ax.yaxis.set_label_coords(0.05, 0.85)

  return
コード例 #27
0
ファイル: yaveroglu.py プロジェクト: rcharbey/Yaveroglu
    def run(self):
        while not self.kill_received:
            # Get a task
            try:
                ndumpName = self.work_queue.get_nowait()

                network = readLeda('{0}.gw'.format(ndumpName))
                spectrum = sorted(nx.laplacian_spectrum(network), reverse=True)

                self.result_queue.put((ndumpName, spectrum))
            except Queue.Empty:
                pass
コード例 #28
0
def plot_spectral_laplacian(graph, filename, label, outpath):
    """ plot spectral distribution of laplacian matrix"""
    if not graph:
        graph = nx.read_edgelist(filename)
    spectrals = nx.laplacian_spectrum(graph)
    spectrals_unique = np.unique(spectrals, return_counts=True)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.bar(spectrals_unique[0], spectrals_unique[1])
    ax.set_title('spectral distribution of laplacian matrix')
    ax.set_xlabel('eigenvalue')
    ax.set_ylabel('frequency')
    plt.savefig(outpath + label + '-spectral-laplacian.svg')
コード例 #29
0
ファイル: WntrMultiDiGraph.py プロジェクト: xmduhan/WNTR
    def algebraic_connectivity(self):
        """ Algebraic connectivity. Second smallest eigenvalue of the normalized
        Laplacian matrix of a network. Uses an undirected graph.
        
        Returns
        -------
        alg_con : float
            Algebraic connectivity
        """
        eig = nx.laplacian_spectrum(self.to_undirected())
        eig = np.sort(eig)
        alg_con = eig[1]

        return alg_con
コード例 #30
0
def lapSpec (graphDic):
    t_list=np.array([])
    eigenval_list=np.array([])
    #for each t all its eigenvalus (eg) in a parallel list
    for T in graphDic.keys():
        graph=(graphDic[T]).to_undirected()
        for ev in np.nditer(nx.laplacian_spectrum(graph)):
            t_list=np.append(t_list, T)
            eigenval_list=np.append( eigenval_list , ev)

    #draw
    plt.plot(t_list, eigenval_list,'ro')
    plt.show()
    return 1
コード例 #31
0
    def laplacian_eigenvalues(self) -> np.array:
        """
        Returns eigenvalues of the Laplacian
        :return:
        """
        CP.print_none('Calculating Laplacian Eigenvalues')
        if self.graph.order() == 0 or self.graph.size() == 0:
            CP.print_orange(
                f'Graph has {self.graph.order()} nodes and {self.graph.size()} edges!'
            )
            laplacian_eigs = []
        else:
            laplacian_eigs = nx.laplacian_spectrum(self.graph)
        self.stats['laplacian_eigenvalues'] = laplacian_eigs

        return laplacian_eigs
コード例 #32
0
ファイル: investigations.py プロジェクト: kpj/OsciPy
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')
コード例 #33
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')
コード例 #34
0
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
コード例 #35
0
 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)
コード例 #36
0
ファイル: t_nx.py プロジェクト: Catentropy/mylab
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)
コード例 #37
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])
コード例 #38
0
    # 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)
コード例 #39
0
    def _compute(self, graph):
        s = nx.laplacian_spectrum(graph)

        return s
コード例 #40
0
 def ComputeLaplacianMatrixEigenvalues(self):
     self.laplacianSpectrum =  np.around(np.array(nx.laplacian_spectrum(self.G)),decimals=4)
     self.laplacianSpectrum.sort()
コード例 #41
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
コード例 #42
0
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')
コード例 #43
0
ファイル: cartesian.py プロジェクト: aweinstein/scrapcode
'''
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])