Example #1
0
File: util.py Project: xgfs/NetLSD
def graph_to_laplacian(G, normalized=True):
    """
    Converts a graph from popular Python packages to Laplacian representation.

    Currently support NetworkX, graph_tool and igraph.
    
    Parameters
    ----------
    G : obj
        Input graph
    normalized : bool
        Whether to use normalized Laplacian.
        Normalized and unnormalized Laplacians capture different properties of graphs, e.g. normalized Laplacian spectrum can determine whether a graph is bipartite, but not the number of its edges. We recommend using normalized Laplacian.

    Returns
    -------
    scipy.sparse
        Laplacian matrix of the input graph

    Examples
    --------
    >>> graph_to_laplacian(nx.complete_graph(3), 'unnormalized').todense()
    [[ 2, -1, -1], [-1,  2, -1], [-1, -1,  2]]

    >>> graph_to_laplacian('test')
    None

    """
    try:
        import networkx as nx
        if isinstance(G, nx.Graph):
            if normalized:
                return nx.normalized_laplacian_matrix(G)
            else:
                return nx.laplacian_matrix(G)
    except ImportError:
        pass
    try:
        import graph_tool.all as gt
        if isinstance(G, gt.Graph):
            if normalized:
                return gt.laplacian_type(G, normalized=True)
            else:
                return gt.laplacian(G)
    except ImportError:
        pass
    try:
        import igraph as ig
        if isinstance(G, ig.Graph):
            if normalized:
                return np.array(G.laplacian(normalized=True))
            else:
                return np.array(G.laplacian())
    except ImportError:
        pass
#Figure 1
gt.graph_draw(G,
              vertex_text=G.vertex_index,
              vertex_font_size=18,
              output_size=(800, 800),
              output="example2.pdf")

#A will be the adjacency matrix of G
A = gt.adjacency(G)

with open('log.txt', 'w') as file_w:
    file_w.write("A_G=\n")
    file_w.write(str(A.todense().transpose()))
    file_w.write("\n")

L = gt.laplacian(G, deg='total', normalized=False, weight=None,
                 index=None)  # unnormalized Laplace
L = L - A.transpose()  #L

with open('log.txt', 'ab') as file_w:
    file_w.write("L=\n")
    file_w.write(str(L.todense()))
    file_w.write("\n")

S, O = numpy.linalg.eigh(L.todense())

with open('log.txt', 'ab') as file_w:
    file_w.write("S=\n")
    file_w.write(str(S))
    file_w.write("\n")

with open('log.txt', 'ab') as file_w: