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


Python Graph.add_nodes_from方法代码示例

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


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

示例1: generate_small_world_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
 def generate_small_world_graph(self):
     max_edges = self.NODE_COUNT*(self.NODE_COUNT-1)/2
     if self.EDGE_COUNT > max_edges:
         return complete_graph(self.NODE_COUNT)
     graph = Graph()
     graph.add_nodes_from(range(self.NODE_COUNT))
     edges = performer.edge_indices.flatten()
     probabilities = performer.probabilities.flatten()
     for trial in range(len(edges)-9):
         edge_index = numpy.random.choice(edges, p=probabilities)
         source, destination = self.edge_nodes(edge_index)
         graph.add_edge(source, destination, length = self.link_length(source, destination),
                        weight = self.edge_weight(source, destination))
         probabilities[edge_index] = 0
         probabilities /= sum(probabilities)
         if max(graph.degree().values()) > self.DEGREE_MAX:
             graph.remove_edge(source, destination)
         if graph.number_of_edges() > self.EDGE_COUNT:
             victim = random.choice(graph.edges())
             graph.remove_edge(victim[0], victim[1])
         if self.constraints_satisfied(graph):
             print 'performer.generate_small_world_graph:',
             print self.BENCHMARK, self.NODE_COUNT, self.EDGE_COUNT, trial
             self.process_graph(graph)
             return graph
开发者ID:yuchenhou,项目名称:artificial-architect,代码行数:27,代码来源:architect.py

示例2: fuzz_network

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def fuzz_network(G_orig, threshold, b, edge_frac=1.0, nonedge_mult=5.0):
    G = G_orig.copy()
    n = len(G.nodes())
    H = Graph()
    H.add_nodes_from(range(n))
    pairs = n * (n - 1) / 2
    actual_edges = len(G.edges())
    edges = int(edge_frac * actual_edges)
    nonedges = int(edges * nonedge_mult)

    a = b / nonedge_mult

    # though these distributions are normalized to one, by selecting the appropriate number of edges
    # and nonedges, we make these 'distributions' correct
    edge_probs = np.random.beta(a + 1, b, edges)
    nonedge_probs = np.random.beta(a, b + 1, nonedges)

    # picking the right number of edges from the appropriate list
    edge_list = G.edges()
    nonedge_list = list(non_edges(G))
    shuffle(edge_list)
    shuffle(nonedge_list)
    for i in range(len(edge_probs)):
        G[edge_list[i][0]][edge_list[i][1]]["weight"] = edge_probs[i]
        if edge_probs[i] > threshold:
            H.add_edge(edge_list[i][0], edge_list[i][1])
    for i in range(len(nonedge_probs)):
        G.add_edge(nonedge_list[i][0], nonedge_list[i][1], weight=nonedge_probs[i])
        if nonedge_probs[i] > threshold:
            H.add_edge(nonedge_list[i][0], nonedge_list[i][1])

    return G, H
开发者ID:tbmbob,项目名称:uncertain-networks,代码行数:34,代码来源:utils.py

示例3: tuples_to_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def tuples_to_graph(tuples):
    G = Graph()
    for node, attribute in tuples:
        print 'adding', node, attribute
        G.add_nodes_from(node, freq=attribute)
        G.add_edges_from(to_edges(node))
    return G
开发者ID:asvishen,项目名称:Factoid-Question-Answering,代码行数:9,代码来源:color.py

示例4: convert_local_tree_topology_to_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def convert_local_tree_topology_to_graph(loc_tree_topo, tree_node_labeling):
    """ Creates a directed, acyclic NetworkX graph from a local tree topology

    Parameters
    ----------
    loc_tree_topo: array-like
        The local tree toplogy, where the root node element is -1

    tree_node_labeling: array-like
        The integer ids for each tree node

    Returns
    -------
    G : NetworkX graph

    """

    assert( loc_tree_topo[0] == -1 )

    G = Graph()
    G.add_nodes_from( tree_node_labeling )
    # build up graph connectivity
    con = vstack( (loc_tree_topo, range(len(loc_tree_topo))) )
    # prune root node connectivity
    con = con[:,1:]
    # update with correct labels
    con = tree_node_labeling[con]
    G.add_edges_from( zip(con[0,:], con[1,:]) )

    return G
开发者ID:unidesigner,项目名称:unidesign,代码行数:32,代码来源:tree.py

示例5: make_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def make_graph(points, neighbor_max_dist=0.01):
    graph = Graph()
    graph.add_nodes_from(range(len(points)))
    for i in xrange(len(points)):
        for j in xrange(i+1, len(points)):
            if euclidian_3d_dist(points[i], points[j])<neighbor_max_dist:
                graph.add_edge(i,j)
    return graph
开发者ID:ChenyuLInx,项目名称:ece490-s2016,代码行数:10,代码来源:common_utils.py

示例6: eliminate_node

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def eliminate_node(G, a):
    fillins = ()
    nb = frozenset(G.neighbors(a))
    for u in nb:
        for v in nb - frozenset((u,)):
            if not G.has_edge(v, u) and frozenset((u, v)) not in fillins:
                fillins += (frozenset((u, v)),)
    kill_edges = frozenset([(u, a) for u in nb] + [(a, u) for u in nb])
    H = Graph()
    H.add_nodes_from(list(frozenset(G.nodes()) - frozenset((a,))))
    H.add_edges_from(list((frozenset(G.edges()) - kill_edges) | frozenset(fillins)))
    return H
开发者ID:darabbt,项目名称:les,代码行数:14,代码来源:minfill.py

示例7: __init__

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
    def __init__(self, mol, eps):
        G = Graph()

        G.add_nodes_from(a.GetIdx() for a in mol.GetAtoms())

        for bond in mol.GetBonds():
            a = bond.GetBeginAtom()
            b = bond.GetEndAtom()

            w = a.GetDegree() * b.GetDegree()

            G.add_edge(a.GetIdx(), b.GetIdx(), weight=w)

        self.G = G
        self.lim = int(1.0 / (eps ** 2))
开发者ID:mordred-descriptor,项目名称:mordred,代码行数:17,代码来源:MolecularId.py

示例8: _build_authors_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
    def _build_authors_graph(self):
        """
        Build authors graph with each author name as nodes and the collaboration between them as edges.

        @author 1: CipherHat

        @rtype:   networkx.Graph()
        @return:  the Graph containing nodes and edges
        """
        all_data = self.get_network_data()
        # TODO refactor: revision on this part. whether to move the Graph code to its own class
        graph = Graph()
        # the nodes format will be {"id":int, "name":str}
        graph.add_nodes_from([(i, {"name": all_data[0][i][0]}) for i in range(len(all_data[0]))])
        graph.add_edges_from(all_data[1])
        return graph
开发者ID:JeffriesAgile,项目名称:comp61542-2014-lab,代码行数:18,代码来源:database.py

示例9: get_coauthor_graph_by_author_name

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
    def get_coauthor_graph_by_author_name(self, name):
        coauthors = set()
        for p in self.publications:
            for a in p.authors:
                if a == self.author_idx[name]:
                    for a2 in p.authors:
                        if a != a2:
                            coauthors.add(a2)

        graph = Graph()
        # the nodes format will be {"id":int, "name":str}
        graph.add_node(self.author_idx[name], name = name)
        # graph.add_nodes_from([(i, {"name": all_data[0][i][0]}) for i in range(len(all_data[0]))])
        graph.add_nodes_from([(ca, {"name": self.authors[ca].name}) for ca in coauthors])
        graph.add_edges_from([(self.author_idx[name], ca) for ca in coauthors])

        return graph
开发者ID:JeffriesAgile,项目名称:comp61542-2014-lab,代码行数:19,代码来源:database.py

示例10: calculate

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
    def calculate(self, P):
        C = self._prop.carbon

        G = Graph()

        G.add_nodes_from(a.GetIdx() for a in self.mol.GetAtoms())

        for bond in self.mol.GetBonds():
            i = bond.GetBeginAtomIdx()
            j = bond.GetEndAtomIdx()

            pi = bond.GetBondTypeAsDouble()

            with self.rethrow_zerodiv():
                w = (C * C) / (P[i] * P[j] * pi)

            G.add_edge(i, j, weight=w)

        sp = floyd_warshall_numpy(G)
        np.fill_diagonal(sp, [1. - C / P[a.GetIdx()] for a in self.mol.GetAtoms()])
        return sp
开发者ID:mordred-descriptor,项目名称:mordred,代码行数:23,代码来源:BaryszMatrix.py

示例11: merge_slices_to_events

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
	def merge_slices_to_events(self, current_slices):
		"""
		Method merges DBSCAN-generated event slices with previously found events. 
		Bimodal network is used to find connections between events and slices,
		then slices are being merged with events, or transformed to new ones.
		Merged events are being deleted.

		Args:
			current_slices (Dict(List[Dict])): output of self.current_datapoints_dbscan method. Every item of dict is a slice cluster: list with dicts of messages from that cluster.
		"""
		slices_ids = set(current_slices.keys())
		events_ids = set(self.events.keys())
		edges = []
		for slice_id, event_slice in current_slices.items():
			slice_ids = {x['id'] for x in event_slice}
			for event in self.events.values():
				if event.is_successor(slice_ids):
					edges.append((slice_id, event.id))
		G = Graph()
		G.add_nodes_from(slices_ids.union(events_ids))
		G.add_edges_from(edges)
		events_to_delete = []
		for cluster in [x for x in connected_components(G) if x.intersection(slices_ids)]:
			unify_slices = cluster.intersection(slices_ids)
			unify_events = list(cluster.intersection(events_ids))
			meta_slice = [msg for i in unify_slices for msg in current_slices[i]]
			if not unify_events:
				new_event = Event(self.mysql, self.redis, self.tokenizer, self.morph, self.classifier, meta_slice)
				self.events[new_event.id] = new_event
			elif len(unify_events) == 1 and len(unify_slices) == 1 and set(self.events[unify_events[0]].messages.keys()) == {x['id'] for x in meta_slice}:
				continue
			else:
				if len(unify_events) > 1:
					for ancestor in unify_events[1:]:
						self.events[unify_events[0]].merge(self.events[ancestor])
						events_to_delete.append(ancestor)
				self.events[unify_events[0]].add_slice(meta_slice)
		for event in events_to_delete:
			del self.events[event]
			self.redis.delete("event:{}".format(event))
开发者ID:city-pulse,项目名称:mskpulse.backend,代码行数:42,代码来源:detector.py

示例12: maotree_old

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def maotree_old(g, m):
    from networkx import Graph, connected_components
    if len(m) == 0:
        return None

    T = Tree(None, [])
    # node -> index in mao
    o = dict((v,i) for i,v in enumerate(m))
    # list of edges (u,v) with o[u] <= o[v]
    e = [(u,v) if o[u] <= o[v] else (v,u) for u,v in g.edges()]
    # we sort e w.r.t. to o such that we can disregard the entire prefix
    # up to the first pair (u,v) with o[u] >= o[current node]
    e.sort(key=lambda (u,v): (o[u], o[v]))
    # todo is a tuple of the current tree node,
    # the remaining mao to process and
    # the offset of the edges to be considered in the
    # edge list e
    todo = [(T, m, 0)]
    while len(todo):
        t, m, i = todo.pop()
        # x = m.pop(0)
        x = m[0]
        t.tag = x
        if len(m) <= 1:
            continue
        while i < len(e) and o[e[i][0]] <= o[x]:
            i = i+1
        g_ = Graph()
        for (u,v) in e[i:]:
            g_.add_edge(u,v)
        g_.add_nodes_from(m[1:])
        cs = connected_components(g_)
        for c in cs:
            c.sort(key=o.get)
        t.children = [Tree(None, []) for c in cs]
        todo.extend(zip(t.children, cs, (i for c in cs)))
    return T
开发者ID:Janno,项目名称:kblocks,代码行数:39,代码来源:mao.py

示例13: to_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def to_graph(l):
    G = Graph()
    for clique in l:
        G.add_nodes_from(clique)
        G.add_edges_from(to_edges(clique))
    return G
开发者ID:asvishen,项目名称:Factoid-Question-Answering,代码行数:8,代码来源:color.py

示例14: FrameworkFeatureAnalyzer

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
class FrameworkFeatureAnalyzer(object):
    """ A class to do feature location analyses on a project written in a specific framework

        Project Graph Details:
        -----------------------
        Node Groups:
            1: Android package
            2: -
            3: Android imported indentifier
            4: Java class
            5: Java method
            6: XML file Category
            7: XML file

        Edge Groups:
            1: internal/hierarchical links
            2: Java---Android mappings
            3: Java---XML mappings
    """

    def __init__(self, framework, project):
        """
            :param inspector.models.base.Project project: the project to be analyzed
        """
        self.project = project

        self.framework_namespace = str(framework)
        self.graph = Graph()
        self.graph.add_node(self.framework_namespace)
        self.import_usages = []

    def add_source_file(self, source_file):
        """
            :param inspector.models.base.SourceFile source_file: the file
        """
        self.analyze_framework_imports(source_file)
        self.analyze_source(source_file)

    def analyze_framework_imports(self, source_file):
        """
            :param inspector.models.base.SourceFile source_file: the file
        """
        for im in source_file.imports:
            if im.import_str.startswith(self.framework_namespace):
                self.import_usages.append((im, im.find_usages()))

                components = im.import_str.split('.')

                data = {'group': 1}
                if re.match(r'^[A-Z]+(_[A-Z]+)*$', components[-1]):
                    data['group'] = 3

                last = None
                for i in range(len(components)):
                    cn = '.'.join(components[:i + 1])
                    self.graph.add_node(cn, **data)
                    if last:
                        self.graph.add_edge(last, cn, weight=1, group=1)
                    last = cn
                if last:
                    data['group'] = 3
                    self.graph.add_node(last, **data)

    def analyze_source(self, source_file):
        """
            :param inspector.models.base.SourceFile source_file: the file
        """
        for cl in source_file.classes:
            self.graph.add_node(cl.name, group=4)
            for fu in cl.methods:
                # print '[{0}-{1}]'.format(fu.starting_line, fu.ending_line), re.sub('\s*\n\s*', ' ', unicode(fu))
                fn = fu.qualified_name
                self.graph.add_node(fn, group=5)
                self.graph.add_edge(cl.name, fn, weight=1, group=1)
                for im, usages in self.import_usages:
                    w = 0
                    for ln in usages:
                        if fu.starting_line <= ln <= fu.ending_line:
                            w += 1
                    if w:
                        self.graph.add_edge(im.import_str, fn, weight=w, group=2)

    def add_xml_files(self):
        xml_sub_groups = {':layout', ':values', ':drawable', ':menu', ':xml', ':color'}
        self.graph.add_nodes_from([':XML'] + list(xml_sub_groups), group=6)
        self.graph.add_edges_from([(':XML', g) for g in xml_sub_groups], weight=1, group=1)
        for path in self.project.filter_files(extension='xml'):
            xml_file = self.project.get_file(path)

            if path.startswith('app/res/'):
                g = path.split('/')[2]
                name = '/'.join(path.split('/')[2:])
                self.graph.add_node(name, group=7)
            else:
                if not path.split('/')[-1] in ['pom.xml', 'AndroidManifest.xml']:  # is ignored?
                    print 'invalid path:', path
                continue

            valid_group = False
            if g == 'values':
#.........这里部分代码省略.........
开发者ID:nvdnkpr,项目名称:static-inspector,代码行数:103,代码来源:framework_feature_analyzer.py

示例15: multigraph_to_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_nodes_from [as 别名]
def multigraph_to_graph(g: MultiGraph) -> Graph:
    gx = Graph()
    gt = Graph(g)
    gx.add_nodes_from(gt.nodes())
    gx.add_edges_from(gt.edges())
    return gx
开发者ID:chinhodado,项目名称:CSI4105-Project,代码行数:8,代码来源:utils.py


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