Python graph_tool.Graph() Examples

The following are 30 code examples of graph_tool.Graph(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module graph_tool , or try the search function .
Example #1
Source File: graph_utils.py    From object_detection_kitti with Apache License 2.0 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #2
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_degree(self):
        graph = graphs.Graph([
            [0, 1, 0],
            [1, 0, 2],
            [0, 2, 0],
        ])
        self.assertEqual(graph.is_directed(), False)
        np.testing.assert_allclose(graph.d, [1, 2, 1])
        np.testing.assert_allclose(graph.dw, [1, 3, 2])
        graph = graphs.Graph([
            [0, 1, 0],
            [0, 0, 2],
            [0, 2, 0],
        ])
        self.assertEqual(graph.is_directed(), True)
        np.testing.assert_allclose(graph.d, [0.5, 1.5, 1])
        np.testing.assert_allclose(graph.dw, [0.5, 2.5, 2]) 
Example #3
Source File: graph_utils.py    From models with Apache License 2.0 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #4
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_is_directed(self):
        graph = graphs.Graph([
            [0, 3, 0, 0],
            [3, 0, 4, 0],
            [0, 4, 0, 2],
            [0, 0, 2, 0],
        ])
        assert graph.W.nnz == 6
        self.assertEqual(graph.is_directed(), False)
        # In-place modification is not allowed anymore.
        # graph.W[0, 1] = 0
        # assert graph.W.nnz == 6
        # self.assertEqual(graph.is_directed(recompute=True), True)
        # graph.W[1, 0] = 0
        # assert graph.W.nnz == 6
        # self.assertEqual(graph.is_directed(recompute=True), False) 
Example #5
Source File: graph_utils.py    From g-tensorflow-models with Apache License 2.0 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #6
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_differential_operator(self, n_vertices=98):
        r"""The Laplacian must always be the divergence of the gradient,
        whether the Laplacian is combinatorial or normalized, and whether the
        graph is directed or weighted."""
        def test_incidence_nx(graph):
            r"""Test that the incidence matrix corresponds to NetworkX."""
            incidence_pg = np.sign(graph.D.toarray())
            G = nx.OrderedDiGraph if graph.is_directed() else nx.OrderedGraph
            graph_nx = nx.from_scipy_sparse_matrix(graph.W, create_using=G)
            incidence_nx = nx.incidence_matrix(graph_nx, oriented=True)
            np.testing.assert_equal(incidence_pg, incidence_nx.toarray())
        for graph in [graphs.Graph(np.zeros((n_vertices, n_vertices))),
                      graphs.Graph(np.identity(n_vertices)),
                      graphs.Graph([[0, 0.8], [0.8, 0]]),
                      graphs.Graph([[1.3, 0], [0.4, 0.5]]),
                      graphs.ErdosRenyi(n_vertices, directed=False, seed=42),
                      graphs.ErdosRenyi(n_vertices, directed=True, seed=42)]:
            for lap_type in ['combinatorial', 'normalized']:
                graph.compute_laplacian(lap_type)
                graph.compute_differential_operator()
                L = graph.D.dot(graph.D.T)
                np.testing.assert_allclose(L.toarray(), graph.L.toarray())
                test_incidence_nx(graph) 
Example #7
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_adjacency_types(self, n_vertices=10):

        rs = np.random.RandomState(42)
        W = 10 * np.abs(rs.normal(size=(n_vertices, n_vertices)))
        W = W + W.T
        W = W - np.diag(np.diag(W))

        def test(adjacency):
            G = graphs.Graph(adjacency)
            G.compute_laplacian('combinatorial')
            G.compute_laplacian('normalized')
            G.estimate_lmax()
            G.compute_fourier_basis()
            G.compute_differential_operator()

        test(W)
        test(W.astype(np.float32))
        test(W.astype(np.int))
        test(sparse.csr_matrix(W))
        test(sparse.csr_matrix(W, dtype=np.float32))
        test(sparse.csr_matrix(W, dtype=np.int))
        test(sparse.csc_matrix(W))
        test(sparse.coo_matrix(W)) 
Example #8
Source File: utils.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def convert_graph_formats(graph, desired_format, directed=None):
    """Converts from/to networkx/igraph


    :param graph: original graph object
    :param desired_format: desired final type. Either nx.Graph or ig.Graph
    :param directed: boolean, default **False**
    :return: the converted graph
    :raises TypeError: if input graph is neither an instance of nx.Graph nor ig.Graph
    """
    if isinstance(graph, desired_format):
        return graph
    elif desired_format is nx.Graph:
        return __from_igraph_to_nx(graph, directed)
    elif ig is not None and desired_format is ig.Graph:
        return __from_nx_to_igraph(graph, directed)
    else:
        raise TypeError(
            "The graph object should be either a networkx or an igraph one.") 
Example #9
Source File: utils.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __from_igraph_to_nx(ig, directed=None):
    """

    :param ig:
    :param directed:
    :return:
    """

    if ig is None:
        raise ModuleNotFoundError(
            "Optional dependency not satisfied: install igraph to use the selected feature.")

    if directed is None:
        directed = ig.is_directed()

    if directed:
        tp = nx.DiGraph()
    else:
        tp = nx.Graph()

    for e in ig.es:
        tp.add_edge(ig.vs[e.source]["name"], ig.vs[e.target]["name"], **e.attributes())


    return tp 
Example #10
Source File: utils.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __from_graph_tool_to_nx(graph, node_map=None, directed=None):

    if directed is None:
        directed = graph.is_directed()

    if directed:
        tp = nx.DiGraph()
    else:
        tp = nx.Graph()

    tp.add_nodes_from([int(v) for v in graph.vertices()])
    tp.add_edges_from([(int(e.source()), int(e.target()))
                       for e in graph.edges()])
    if node_map:
        nx.relabel_nodes(tp, node_map, copy=False)

    return tp 
Example #11
Source File: utils.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __from_nx_to_graph_tool(g, directed=None):
    """

    :param g:
    :param directed:
    :return:
    """

    if directed is None:
        directed = g.is_directed()

    if gt is None:
        raise ModuleNotFoundError(
            "Optional dependency not satisfied: install igraph to use the selected feature.")

    gt_g = gt.Graph(directed=directed)

    node_map = {v: i for i, v in enumerate(g.nodes())}

    gt_g.add_vertex(len(node_map))
    gt_g.add_edge_list([(node_map[u], node_map[v]) for u, v in g.edges()])

    return gt_g, {v: k for k, v in node_map.items()} 
Example #12
Source File: graph_utils.py    From object_detection_with_tensorflow with MIT License 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #13
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_graphtool_multiedge_import(self):
        # Manualy create a graph with multiple edges
        g_gt = gt.Graph()
        g_gt.add_vertex(n=10)
        # connect edge (3,6) three times
        for i in range(3):
            g_gt.add_edge(g_gt.vertex(3), g_gt.vertex(6))
        g = graphs.Graph.from_graphtool(g_gt)
        self.assertEqual(g.W[3, 6], 3.0)

        eprop_double = g_gt.new_edge_property("double")

        # Set the weight of 2 out of the 3 edges. The last one has a default weight of 0
        e = g_gt.edge(3, 6, all_edges=True)
        eprop_double[e[0]] = 8.0
        eprop_double[e[1]] = 1.0

        g_gt.edge_properties["weight"] = eprop_double
        g3 = graphs.Graph.from_graphtool(g_gt)
        self.assertEqual(g3.W[3, 6], 9.0) 
Example #14
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_graphtool_import_export(self):
        # Import to PyGSP and export again to graph tool directly
        # create a random graphTool graph that does not contain multiple edges and no signal
        graph_gt = gt.generation.random_graph(100, lambda : (np.random.poisson(4), np.random.poisson(4)))

        eprop_double = graph_gt.new_edge_property("double")
        for e in graph_gt.edges():
            eprop_double[e] = random.random()
        graph_gt.edge_properties["weight"] = eprop_double

        graph2_gt = graphs.Graph.from_graphtool(graph_gt).to_graphtool()

        self.assertEqual(graph_gt.num_edges(), graph2_gt.num_edges(),
                         "the number of edges does not correspond")

        def key(edge): return str(edge.source()) + ":" + str(edge.target())

        for e1, e2 in zip(sorted(graph_gt.edges(), key=key), sorted(graph2_gt.edges(), key=key)):
            self.assertEqual(e1.source(), e2.source())
            self.assertEqual(e1.target(), e2.target())
        for v1, v2 in zip(graph_gt.vertices(), graph2_gt.vertices()):
            self.assertEqual(v1, v2) 
Example #15
Source File: graph_utils.py    From Gun-Detector with Apache License 2.0 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #16
Source File: graph_utils.py    From multilabel-image-classification-tensorflow with MIT License 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #17
Source File: graph_utils.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #18
Source File: graph_utils.py    From yolo_v2 with Apache License 2.0 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #19
Source File: graph_utils.py    From hands-detection with MIT License 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #20
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_break_join_signals(self):
        """Multi-dim signals are broken on export and joined on import."""
        graph1 = graphs.Sensor(20, seed=42)
        graph1.set_signal(graph1.coords, 'coords')
        # networkx
        graph2 = graph1.to_networkx()
        graph2 = graphs.Graph.from_networkx(graph2)
        np.testing.assert_allclose(graph2.signals['coords'], graph1.coords)
        # graph-tool
        graph2 = graph1.to_graphtool()
        graph2 = graphs.Graph.from_graphtool(graph2)
        np.testing.assert_allclose(graph2.signals['coords'], graph1.coords)
        # save and load (need ordered dicts)
        if sys.version_info >= (3, 6):
            filename = 'graph.graphml'
            graph1.save(filename)
            graph2 = graphs.Graph.load(filename)
            np.testing.assert_allclose(graph2.signals['coords'], graph1.coords)
            os.remove(filename) 
Example #21
Source File: utils.py    From epiScanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_graph_tool_from_adjacency(adjacency, directed=None):
    """Get graph_tool graph from adjacency matrix."""
    import graph_tool as gt
    adjacency_edge_list = adjacency
    if not directed:
        from scipy.sparse import tril
        adjacency_edge_list = tril(adjacency)
    g = gt.Graph(directed=directed)
    g.add_vertex(adjacency.shape[0])  # this adds adjacency.shap[0] vertices
    g.add_edge_list(np.transpose(adjacency_edge_list.nonzero()))
    weights = g.new_edge_property('double')
    for e in g.edges():
        # graph_tool uses the following convention,
        # which is opposite to the rest of scanpy
        weights[e] = adjacency[int(e.source()), int(e.target())]
    g.edge_properties['weight'] = weights
    return g 
Example #22
Source File: utils.py    From epiScanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_igraph_from_adjacency(adjacency, directed=None):
    """Get igraph graph from adjacency matrix."""
    import igraph as ig
    sources, targets = adjacency.nonzero()
    weights = adjacency[sources, targets]
    if isinstance(weights, np.matrix):
        weights = weights.A1
    g = ig.Graph(directed=directed)
    g.add_vertices(adjacency.shape[0])  # this adds adjacency.shap[0] vertices
    g.add_edges(list(zip(sources, targets)))
    try:
        g.es['weight'] = weights
    except:
        pass
    if g.vcount() != adjacency.shape[0]:
        logg.warn('The constructed graph has only {} nodes. '
                  'Your adjacency matrix contained redundant nodes.'
                  .format(g.vcount()))
    return g 
Example #23
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_graphtool_signal_import(self):
        g_gt = gt.Graph()
        g_gt.add_vertex(10)

        g_gt.add_edge(g_gt.vertex(3), g_gt.vertex(6))
        g_gt.add_edge(g_gt.vertex(4), g_gt.vertex(6))
        g_gt.add_edge(g_gt.vertex(7), g_gt.vertex(2))

        vprop_double = g_gt.new_vertex_property("double")

        vprop_double[g_gt.vertex(0)] = 5
        vprop_double[g_gt.vertex(1)] = -3
        vprop_double[g_gt.vertex(2)] = 2.4

        g_gt.vertex_properties["signal"] = vprop_double
        g = graphs.Graph.from_graphtool(g_gt)
        self.assertEqual(g.signals["signal"][0], 5.0)
        self.assertEqual(g.signals["signal"][1], -3.0)
        self.assertEqual(g.signals["signal"][2], 2.4) 
Example #24
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_line_graph(self):
        adjacency = [
            [0, 1, 1, 3],
            [1, 0, 1, 0],
            [1, 1, 0, 1],
            [3, 0, 1, 0],
        ]
        coords = [
            [0, 0],
            [4, 0],
            [4, 2],
            [0, 2],
        ]
        graph = graphs.Graph(adjacency, coords=coords)
        graph = graphs.LineGraph(graph)
        adjacency = [
            [0, 1, 1, 1, 0],
            [1, 0, 1, 1, 1],
            [1, 1, 0, 0, 1],
            [1, 1, 0, 0, 1],
            [0, 1, 1, 1, 0],
        ]
        coords = [
            [2, 0],
            [2, 1],
            [0, 1],
            [4, 1],
            [2, 2],
        ]
        np.testing.assert_equal(graph.W.toarray(), adjacency)
        np.testing.assert_equal(graph.coords, coords)
        if sys.version_info > (3, 4):  # no assertLogs in python 2.7
            with self.assertLogs(level='WARNING'):
                graphs.LineGraph(graphs.Graph([[0, 2], [2, 0]])) 
Example #25
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_networkx_export_import(self):
        # Export to networkx and reimport to PyGSP

        # Exporting the Bunny graph
        g = graphs.Bunny()
        g_nx = g.to_networkx()
        g2 = graphs.Graph.from_networkx(g_nx)
        np.testing.assert_array_equal(g.W.todense(), g2.W.todense()) 
Example #26
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_graphtool_export_import(self):
        # Export to graph tool and reimport to PyGSP directly
        # The exported graph is a simple one without an associated Signal
        g = graphs.Bunny()
        g_gt = g.to_graphtool()
        g2 = graphs.Graph.from_graphtool(g_gt)
        np.testing.assert_array_equal(g.W.todense(), g2.W.todense()) 
Example #27
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_save_load(self):

        # TODO: test with multiple graphs and signals
        # * dtypes (float, int, bool) of adjacency and signals
        # * empty graph / isolated nodes

        G1 = graphs.Sensor(seed=42)
        W = G1.W.toarray()
        sig = np.random.RandomState(42).normal(size=G1.N)
        G1.set_signal(sig, 's')

        for fmt in ['graphml', 'gml', 'gexf']:
            for backend in ['networkx', 'graph-tool']:

                if fmt == 'gexf' and backend == 'graph-tool':
                    self.assertRaises(ValueError, G1.save, 'g', fmt, backend)
                    self.assertRaises(ValueError, graphs.Graph.load, 'g', fmt,
                                      backend)
                    os.remove('g')
                    continue

                atol = 1e-5 if fmt == 'gml' and backend == 'graph-tool' else 0

                for filename, fmt in [('graph.' + fmt, None), ('graph', fmt)]:
                    G1.save(filename, fmt, backend)
                    G2 = graphs.Graph.load(filename, fmt, backend)
                    np.testing.assert_allclose(G2.W.toarray(), W, atol=atol)
                    np.testing.assert_allclose(G2.signals['s'], sig, atol=atol)
                    os.remove(filename)

        self.assertRaises(ValueError, graphs.Graph.load, 'g.gml', fmt='?')
        self.assertRaises(ValueError, graphs.Graph.load, 'g.gml', backend='?')
        self.assertRaises(ValueError, G1.save, 'g.gml', fmt='?')
        self.assertRaises(ValueError, G1.save, 'g.gml', backend='?') 
Example #28
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_import_errors(self):
        from unittest.mock import patch
        graph = graphs.Sensor()
        filename = 'graph.gml'
        with patch.dict(sys.modules, {'networkx': None}):
            self.assertRaises(ImportError, graph.to_networkx)
            self.assertRaises(ImportError, graphs.Graph.from_networkx, None)
            self.assertRaises(ImportError, graph.save, filename,
                              backend='networkx')
            self.assertRaises(ImportError, graphs.Graph.load, filename,
                              backend='networkx')
            graph.save(filename)
            graphs.Graph.load(filename)
        with patch.dict(sys.modules, {'graph_tool': None}):
            self.assertRaises(ImportError, graph.to_graphtool)
            self.assertRaises(ImportError, graphs.Graph.from_graphtool, None)
            self.assertRaises(ImportError, graph.save, filename,
                              backend='graph-tool')
            self.assertRaises(ImportError, graphs.Graph.load, filename,
                              backend='graph-tool')
            graph.save(filename)
            graphs.Graph.load(filename)
        with patch.dict(sys.modules, {'networkx': None, 'graph_tool': None}):
            self.assertRaises(ImportError, graph.save, filename)
            self.assertRaises(ImportError, graphs.Graph.load, filename)
        os.remove(filename) 
Example #29
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_graph(self, n_vertices=11):
        """Empty graphs have either no edge, or self-loops only. The Laplacian
        doesn't see self-loops, as the gradient on those edges is always zero.
        """
        adjacencies = [
            np.zeros((n_vertices, n_vertices)),
            np.identity(n_vertices),
        ]
        for adjacency, n_edges in zip(adjacencies, [0, n_vertices]):
            graph = graphs.Graph(adjacency)
            self.assertEqual(graph.n_vertices, n_vertices)
            self.assertEqual(graph.n_edges, n_edges)
            self.assertEqual(graph.W.nnz, n_edges)
            for laplacian in ['combinatorial', 'normalized']:
                graph.compute_laplacian(laplacian)
                self.assertEqual(graph.L.nnz, 0)
                sources, targets, weights = graph.get_edge_list()
                self.assertEqual(len(sources), n_edges)
                self.assertEqual(len(targets), n_edges)
                self.assertEqual(len(weights), n_edges)
                graph.compute_differential_operator()
                self.assertEqual(graph.D.nnz, 0)
                graph.compute_fourier_basis()
                np.testing.assert_allclose(graph.U, np.identity(n_vertices))
                np.testing.assert_allclose(graph.e, np.zeros(n_vertices))
            # NetworkX uses the same conventions.
            G = nx.from_scipy_sparse_matrix(graph.W)
            self.assertEqual(nx.laplacian_matrix(G).nnz, 0)
            self.assertEqual(nx.normalized_laplacian_matrix(G).nnz, 0)
            self.assertEqual(nx.incidence_matrix(G).nnz, 0) 
Example #30
Source File: graph_utils.py    From g-tensorflow-models with Apache License 2.0 5 votes vote down vote up
def get_distance_node_list(gtG, source_nodes, direction, weights=None):
  gtG_ = gt.Graph(gtG)
  v = gtG_.add_vertex()

  if weights is not None:
    weights = gtG_.edge_properties[weights]

  for s in source_nodes:
    e = gtG_.add_edge(s, int(v))
    if weights is not None:
      weights[e] = 0.

  if direction == 'to':
    dist = gt.topology.shortest_distance(
        gt.GraphView(gtG_, reversed=True), source=gtG_.vertex(int(v)),
        target=None, weights=weights)
  elif direction == 'from':
    dist = gt.topology.shortest_distance(
        gt.GraphView(gtG_, reversed=False), source=gtG_.vertex(int(v)),
        target=None, weights=weights)
  dist = np.array(dist.get_array())
  dist = dist[:-1]
  if weights is None:
    dist = dist-1
  return dist

# Functions for semantically labelling nodes in the traversal graph.