当前位置: 首页>>代码示例>>Python>>正文


Python Graph.add_edge方法代码示例

本文整理汇总了Python中graph_tool.Graph.add_edge方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_edge方法的具体用法?Python Graph.add_edge怎么用?Python Graph.add_edge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在graph_tool.Graph的用法示例。


在下文中一共展示了Graph.add_edge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: gen_cascade

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def gen_cascade(g, p, source=None, stop_fraction=0.5):
    if source is None:
        source = random.choice(np.arange(g.num_vertices()))
    infected = {source}
    infection_times = np.ones(g.num_vertices()) * -1
    infection_times[source] = 0
    time = 0
    edges = []
    while np.count_nonzero(infection_times != -1) / g.num_vertices() <= stop_fraction:
        infected_nodes_until_t = copy(infected)
        time += 1
        for i in infected_nodes_until_t:
            for j in g.vertex(i).all_neighbours():
                j = int(j)
                if j not in infected and random.random() <= p:
                    infected.add(j)
                    infection_times[j] = time
                    edges.append((i, j))

    tree = Graph(directed=True)
    for _ in range(g.num_vertices()):
        tree.add_vertex()
    for u, v in edges:
        tree.add_edge(u, v)
    return source, infection_times, tree
开发者ID:xiaohan2012,项目名称:active-infection-source-finding,代码行数:27,代码来源:si.py

示例2: build_minimum_tree

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def build_minimum_tree(g, root, terminals, edges, directed=True):
    """remove redundant edges from `edges` so that root can reach each node in terminals
    """
    # build the tree
    t = Graph(directed=directed)

    for _ in range(g.num_vertices()):
        t.add_vertex()

    for (u, v) in edges:
        t.add_edge(u, v)

    # mask out redundant edges
    vis = init_visitor(t, root)
    pbfs_search(t, source=root, terminals=list(terminals), visitor=vis)

    minimum_edges = {e
                     for u in terminals
                     for e in extract_edges_from_pred(t, root, u, vis.pred)}
    # print(minimum_edges)
    efilt = t.new_edge_property('bool')
    efilt.a = False
    for u, v in minimum_edges:
        efilt[u, v] = True
    t.set_edge_filter(efilt)

    return filter_nodes_by_edges(t, minimum_edges)
开发者ID:xiaohan2012,项目名称:active-infection-source-finding,代码行数:29,代码来源:utils.py

示例3: ring

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def ring(num_vtx=100, k=2, p=0.0):
    g = Graph(directed=False)
    vtx = list(g.add_vertex(num_vtx))

    # connect neighbors
    for i in vtx:
        for j in xrange(1, k + 1):
            dest = g.vertex((g.vertex_index[i] - j) % num_vtx)
            if g.edge(i, dest) is None:
                g.add_edge(i, dest)

    # redirect edges
    # old_edges = list(g.edges())
    old_edges = [(x.source(), x.target()) for x in g.edges()]
    for i in old_edges:
        n = random.random()
        if n < p:  # redirect edge; choose random vertex as new destination
            vtx_tmp = vtx[:]
            vtx_tmp.remove(i[1])
            if i[0] in vtx_tmp:
                vtx_tmp.remove(i[0])
            dest = random.choice(vtx_tmp)
            while g.edge(i[0], dest) is not None:
                vtx_tmp.remove(dest)
                dest = random.choice(vtx_tmp)

            g.remove_edge(g.edge(i[0], i[1]))
            g.add_edge(i[0], dest)

    return g
开发者ID:kroq-gar78,项目名称:BigGraphAnalysis,代码行数:32,代码来源:graph_generate.py

示例4: _filter_short_branch

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
    def _filter_short_branch(self, filter=False, short=30):
        """
        filter out very short branches: do this maybe not right for some models, for models with flat part, it is right
        I will test how this effect the final matching results
        need to delete nodes, switch with the last one then delete last
        """
        if filter == False:
            self.verts = self.verts_init
            self.edges = self.edges_init
        else:
            init_graph = Graph(directed=False)
            init_graph.add_vertex(len(self.verts_init))
            for edge in self.edges_init:
                init_graph.add_edge(init_graph.vertex(edge[0]), init_graph.vertex(edge[1]))

            terminal_node = []
            for v in init_graph.vertices():
                if v.out_degree() == 1:
                    terminal_node.append(v)

            visitor = DepthVisitor()
            short_nodes = []
            for tn in terminal_node:
                search.dfs_search(init_graph, tn, visitor)
                tmp_node = visitor.get_short_branch(min_length=short)
                visitor.reset()
                for n in tmp_node:
                    short_nodes.append(n)

            ## get edges on the short paths
            short_nodes = list(set(short_nodes))
            short_edges = []
            temp_verts = self.verts_init[:]
            v_num = len(self.verts_init)
            if len(short_nodes):
                for v in reversed(sorted(short_nodes)):
                    for ve in init_graph.vertex(v).out_edges():
                        short_edges.append(ve)

                ## delete edges first, then vertex
                short_edges = list(set(short_edges))
                for e in short_edges:
                    init_graph.remove_edge(e)

                print 'deleting vertex',
                for v in reversed(sorted(short_nodes)):
                    print v,
                    temp_verts[int(v)] = temp_verts[v_num-1]
                    init_graph.remove_vertex(v, fast=True)
                    v_num -= 1
                print '\ndeleting related edges' # already done above, just info user
            else:
                print 'no short branches'

            ######## new vertices and edges ########
            self.verts = temp_verts[:v_num]
            self.edges = []
            for e in init_graph.edges():
                self.edges.append([int(e.source()), int(e.target())])
开发者ID:bo-wu,项目名称:skel_corres,代码行数:61,代码来源:skeleton_data.py

示例5: edges2graph

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def edges2graph(g, edges):
    tree = Graph(directed=True)
    for _ in range(g.num_vertices()):
        tree.add_vertex()
    for u, v in edges:
        tree.add_edge(int(u), int(v))

    return filter_nodes_by_edges(tree, edges)
开发者ID:xiaohan2012,项目名称:active-infection-source-finding,代码行数:10,代码来源:utils.py

示例6: steiner_tree_greedy

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def steiner_tree_greedy(
        g, root, infection_times, source, obs_nodes,
        debug=False,
        verbose=True):
    # root = min(obs_nodes, key=infection_times.__getitem__)
    sorted_obs = list(sorted(obs_nodes, key=infection_times.__getitem__))[1:]
    tree_nodes = {root}
    tree_edges = set()
    for u in sorted_obs:
        # connect u to the tree
        vis = init_visitor(g, u)
        if debug:
            print('connect {} to tree'.format(u))
            print('nodes connectable: {}'.format(tree_nodes))
        forbidden_nodes = list(set(obs_nodes) - tree_nodes)
        cpbfs_search(g, u, visitor=vis,
                     terminals=list(tree_nodes),
                     forbidden_nodes=forbidden_nodes,
                     count_threshold=1)

        # add edge
        reachable_nodes = set(np.nonzero(vis.dist > 0)[0]).intersection(tree_nodes)

        if debug:
            print('reachable_nodes: {}'.format(reachable_nodes))

        assert len(reachable_nodes) > 0
        sorted_ancestors = sorted(reachable_nodes, key=vis.dist.__getitem__)
        ancestor = sorted_ancestors[0]

        if debug:
            print('ancestor: {}'.format(ancestor))
            print('dist to reachable: {}'.format(vis.dist[sorted_ancestors]))

        new_edges = extract_edges_from_pred(g, u, ancestor, vis.pred)
        new_edges = {(v, u) for u, v in new_edges}  # needs to reverse the order

        if debug:
            print('new_edges: {}'.format(new_edges))

        tree_edges |= set(new_edges)
        tree_nodes |= {v for e in new_edges for v in e}

    t = Graph(directed=True)
    for _ in range(g.num_vertices()):
        t.add_vertex()

    vfilt = t.new_vertex_property('bool')
    vfilt.a = False
    for v in tree_nodes:
        vfilt[t.vertex(v)] = True

    for u, v in tree_edges:
        t.add_edge(t.vertex(u), t.vertex(v))

    t.set_vertex_filter(vfilt)

    return t
开发者ID:xiaohan2012,项目名称:active-infection-source-finding,代码行数:60,代码来源:steiner_tree_greedy.py

示例7: to_directed

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def to_directed(g, t, root):
    new_t = Graph(directed=True)
    all_edges = set()
    leaves = [v for v in t.vertices()
              if (v.out_degree() + v.in_degree()) == 1 and t != root]
    for target in leaves:
        path = shortest_path(t, source=root, target=target)[0]
        edges = set(zip(path[:-1], path[1:]))
        all_edges |= edges

    for _ in range(g.num_vertices()):
        new_t.add_vertex()
    for u, v in all_edges:
        new_t.add_edge(int(u), int(v))
    return new_t
开发者ID:xiaohan2012,项目名称:active-infection-source-finding,代码行数:17,代码来源:utils.py

示例8: RoadMap

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
class RoadMap(object):
    def __init__(self, mapfile):
        self._mapfile = mapfile
        self.DIRECTION_index = 6
        self.PATHCLASS_index = 20
        self.g = Graph()
        self.g.edge_properties["length"] = self.g.new_edge_property("double")
        self.g.edge_properties["level"] = self.g.new_edge_property("int")
        self.g.vertex_properties["pos"] = self.g.new_vertex_property("vector<double>")
        self.cross_pos_index = {}

    def load(self):
        if self._mapfile[-3:] != 'shp':
            self.g = load_graph(self._mapfile)
            return

        try:
            sf = shapefile.Reader(self._mapfile)
        except Exception as e:
            print(str(e))
            return False
        roads_records = sf.shapeRecords()  # 获取路段信息'
        for road_record in roads_records:
            cross_s_index = self.add_cross(road_record.shape.points[0])
            cross_e_index = self.add_cross(road_record.shape.points[-1])
            self.add_road_edge(cross_s_index, cross_e_index, road_record)
            if int(road_record.record[self.DIRECTION_index]) == 0:  # 若路段是双向车道
                self.add_road_edge(cross_e_index, cross_s_index, road_record)
        return True

    def has_edge(self, s_vertex, e_vertex):
        if self.g.num_vertices() >= max(s_vertex, e_vertex):
            return self.g.edge(s_vertex, e_vertex)
        else:
            return None

    def add_cross(self, cross_pos):
        if cross_pos in self.cross_pos_index:
            return self.cross_pos_index.get(cross_pos)
        else:
            cross_index = self.g.add_vertex()
            self.g.vp.pos[cross_index] = cross_pos
            self.cross_pos_index[cross_pos] = cross_index
            return cross_index

    def add_road_edge(self, s_vertex, e_vertex, road):
        if self.has_edge(s_vertex, e_vertex):
            return self.g.edge(s_vertex, e_vertex)
        else:
            edge = self.g.add_edge(s_vertex, e_vertex)
            self.g.ep.level[edge] = int(road.record[self.PATHCLASS_index])
            self.g.ep.length[edge] = self.road_length(road)
            return edge

    @staticmethod
    def road_length(road):
        length = 0
        for sub_road in zip(road.shape.points[:-1], road.shape.points[1:]):
            length += distance.euclidean(sub_road[0], sub_road[1])
        return length
开发者ID:elvis2els,项目名称:map,代码行数:62,代码来源:gt_roadmap.py

示例9: create_graph

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
    def create_graph(cls, edges, is_directed=True):
        """Create a graph-tool type graph from a list of edges"""
        g = Graph()
        g.set_directed(is_directed)
        label2index = dict()
        label = g.new_vertex_property('int32_t')
        g.vertex_properties['label'] = label

        for v1_label, v2_label in edges:
            cls.add_vertex(v1_label, label2index, g)
            cls.add_vertex(v2_label, label2index, g)

            v1, v2 = label2index[v1_label], label2index[v2_label]
            g.add_edge(v1, v2)

        return g, label2index
开发者ID:kwerenda,项目名称:role-mining,代码行数:18,代码来源:Network.py

示例10: edges_to_directed_tree

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def edges_to_directed_tree(g, root, edges):
    t = Graph(directed=False)
    for _ in range(g.num_vertices()):
        t.add_vertex()

    for u, v in edges:
        t.add_edge(u, v)

    vis = EdgeCollectorVisitor()
    bfs_search(t, source=root, visitor=vis)

    t.clear_edges()
    t.set_directed(True)
    for u, v in vis.edges:
        t.add_edge(u, v)

    return filter_nodes_by_edges(t, edges)
开发者ID:xiaohan2012,项目名称:active-infection-source-finding,代码行数:19,代码来源:gt_utils.py

示例11: compose_graph

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def compose_graph(uid_pid_pairs):

    # set up graph
    g = Graph()
    g.vp['pid'] = v_pid_p = g.new_vertex_property('string')
    g.vp['count'] = v_count_p = g.new_vertex_property('int')
    g.ep['count'] = e_count_p = g.new_edge_property('int')

    pid_v_map = {}
    uid_last_v_map = {}
    vv_e_map = {}

    for uid, pid in uid_pid_pairs:

        # vertex

        v = pid_v_map.get(pid)
        if v is None:
            v = g.add_vertex()
            v_pid_p[v] = pid
            v_count_p[v] = 0
            pid_v_map[pid] = v
        v_count_p[v] += 1

        # edge

        last_v = uid_last_v_map.get(uid)
        uid_last_v_map[uid] = v
        if last_v is None:
            continue

        vv = (last_v, v)
        e = vv_e_map.get(vv)
        if e is None:
            e = g.add_edge(*vv)
            e_count_p[e] = 0
            vv_e_map[vv] = e
        e_count_p[e] += 1

    # calculate closeness
    g.vp['closeness'] = v_closeness_p = g.new_vertex_property('float')
    e_inverse_count_p = g.new_edge_property('int')
    e_inverse_count_p.a = e_count_p.a.max()-e_count_p.a
    debug('e_inverse_count_p.a: {}', e_inverse_count_p.a)
    closeness(g, weight=e_inverse_count_p, vprop=v_closeness_p)
    debug('v_closeness_p.a    : {}', v_closeness_p.a)
    v_closeness_p.a = nan_to_num(v_closeness_p.a)
    debug('v_closeness_p.a    : {}', v_closeness_p.a)

    # fillter
    g.vp['picked'] = v_picked_p = g.new_vertex_property('bool')
    debug('v_count_p.a.mean() : {}', v_count_p.a.mean())
    v_picked_p.a = v_count_p.a > v_count_p.a.mean()
    debug('v_picked_p.a       : {}', v_picked_p.a)
    g.set_vertex_filter(v_picked_p)
    g.set_vertex_filter(None)

    return g
开发者ID:moskytw,项目名称:graph-tool-lab,代码行数:60,代码来源:test_graph_tool.py

示例12: graph_from_dataframes

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def graph_from_dataframes(vertex_df, edge_df):
    '''Re-creates a Graph object with PropertyMaps taken
    from the vertex_df and edge_df DataFrames

    Paramters:
    ==========
    verex_df: a DataFrame with an index named 'vertex_index'
    edge_df: a DataFrame with a multi-index named ('source', 'target')

    Returns:
    ========
    graph: a grah-tool Graph with PropertyMaps copied
        from the columns of the input DataFrames
    '''

    graph = Graph(directed=True)

    vertex_index = vertex_df.index.get_level_values(level='vertex_index')
    vertices = graph.add_vertex(n=vertex_index.shape[0])
    for col in vertex_df.columns:
        in_type = vertex_df[col].dtype.name
        try:
            dtype = ALIASES[in_type]
        except KeyError:
            log.info('Data type {} not supported'.format(in_type))
            continue
        prop = graph.new_vertex_property(dtype)
        prop.fa = vertex_df[col]
        graph.vertex_properties[col] = prop

    src = edge_df.index.names.index('source')
    trgt = edge_df.index.names.index('target')
    ### TODO: use the list edge creation
    for tup in edge_df.index:
        source, target = tup[src], tup[trgt]
        try:
            edge = graph.add_edge(source, target)
        except ValueError:
            log.info('Invalid vertex in (source: {}, target: {})'.format(source, target))
    for col in edge_df.columns:
        in_type = edge_df[col].dtype.name
        try:
            dtype = ALIASES[in_type]
        except KeyError:
            log.info('Data type {} not supported'.format(in_type))
            continue
        prop = graph.new_edge_property(dtype)
        prop.fa = edge_df[col]
        graph.edge_properties[col] = prop

    return graph
开发者ID:DamCB,项目名称:hdfgraph,代码行数:53,代码来源:hdfgraph.py

示例13: build_closure

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def build_closure(g, terminals,
                  debug=False,
                  verbose=False):
    terminals = list(terminals)
    # build closure
    gc = Graph(directed=False)

    for _ in range(g.num_vertices()):
        gc.add_vertex()

    edges_with_weight = set()
    r2pred = {}

    for r in terminals:
        if debug:
            print('root {}'.format(r))
        vis = init_visitor(g, r)
        pbfs_search(g, source=r, terminals=terminals, visitor=vis)
        new_edges = set(get_edges(vis.dist, r, terminals))
        if debug:
            print('new edges {}'.format(new_edges))
        edges_with_weight |= new_edges
        r2pred[r] = vis.pred
    
    for u, v, c in edges_with_weight:
        gc.add_edge(u, v)
        
    eweight = gc.new_edge_property('int')
    weights = np.array([c for _, _, c in edges_with_weight])
    eweight.set_2d_array(weights)

    vfilt = gc.new_vertex_property('bool')
    vfilt.a = False
    for v in terminals:
        vfilt[v] = True
    gc.set_vertex_filter(vfilt)
    return gc, eweight, r2pred
开发者ID:xiaohan2012,项目名称:active-infection-source-finding,代码行数:39,代码来源:steiner_tree.py

示例14: load_graph

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def load_graph(infile):
    inmatrix = np.loadtxt(infile, dtype=np.dtype('uint32'), delimiter=" ")
    numv = np.amax(inmatrix[:,0:2])

    #print numv, inmatrix[:,0:2]

    g = Graph(directed=False)
    edge_weights = g.new_edge_property("double")
    g.edge_properties["weights"] = edge_weights
    vlist = list(g.add_vertex(numv))

    for i in inmatrix:
        edge = g.add_edge(vlist[i[0]-1], vlist[i[1]-1]) # need to convert from 1-based index in file to 0-based
        edge_weights[edge] = i[2]

    remove_parallel_edges(g)
    return g
开发者ID:kroq-gar78,项目名称:BigGraphAnalysis,代码行数:19,代码来源:graph_reader.py

示例15: user_network

# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import add_edge [as 别名]
def user_network(storage, track, session):
    g = Graph()
    users = defaultdict(g.add_vertex)

    g.graph_properties["track"] = g.new_graph_property("string", track)
    g.graph_properties["session"] = g.new_graph_property("string", session)

    g.edge_properties["created_at"] = g.new_edge_property("int64_t")

    for tweet in storage:
        tweeter_id = tweet["user__id_str"]
        origin_id = tweet["retweeted_status__user__id_str"]

        created_at = arrow.get(tweet["created_at"], DATE_FORMAT).timestamp

        if origin_id:
            edge = g.add_edge(users[tweeter_id], users[origin_id])
            g.edge_properties["created_at"][edge] = created_at

    return g
开发者ID:harius,项目名称:twitterology,代码行数:22,代码来源:_networks.py


注:本文中的graph_tool.Graph.add_edge方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。